<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    
    <title>16.4. optparse — More powerful command line option parser &mdash; Python v2.6.2 documentation</title>
    <link rel="stylesheet" href="../_static/default.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript">
      var DOCUMENTATION_OPTIONS = {
        URL_ROOT:    '../',
        VERSION:     '2.6.2',
        COLLAPSE_MODINDEX: false,
        FILE_SUFFIX: '.html',
        HAS_SOURCE:  true
      };
    </script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python v2.6.2 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="top" title="Python v2.6.2 documentation" href="../index.html" />
    <link rel="up" title="16. Generic Operating System Services" href="allos.html" />
    <link rel="next" title="16.5. getopt — Parser for command line options" href="getopt.html" />
    <link rel="prev" title="16.3. time — Time access and conversions" href="time.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
 

  </head>
  <body>
    <div class="related">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../modindex.html" title="Global Module Index"
             accesskey="M">modules</a> |</li>
        <li class="right" >
          <a href="getopt.html" title="16.5. getopt — Parser for command line options"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="time.html" title="16.3. time — Time access and conversions"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="../index.html">Python v2.6.2 documentation</a> &raquo;</li>

          <li><a href="index.html" >The Python Standard Library</a> &raquo;</li>
          <li><a href="allos.html" accesskey="U">16. Generic Operating System Services</a> &raquo;</li> 
      </ul>
    </div>  

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body">
            
  <div class="section" id="module-optparse">
<h1>16.4. <tt class="xref docutils literal"><span class="pre">optparse</span></tt> &#8212; More powerful command line option parser<a class="headerlink" href="#module-optparse" title="Permalink to this headline">¶</a></h1>
<p>
<span class="versionmodified">New in version 2.3.</span></p>
<p><tt class="docutils literal"><span class="pre">optparse</span></tt> is a more convenient, flexible, and powerful library for parsing
command-line options than the old <a title="Portable parser for command line options; support both short and long option names." class="reference external" href="getopt.html#module-getopt"><tt class="xref docutils literal"><span class="pre">getopt</span></tt></a> module.  <tt class="docutils literal"><span class="pre">optparse</span></tt> uses a more declarative
style of command-line parsing: you create an instance of <tt class="xref docutils literal"><span class="pre">OptionParser</span></tt>,
populate it with options, and parse the command line. <tt class="docutils literal"><span class="pre">optparse</span></tt> allows users
to specify options in the conventional GNU/POSIX syntax, and additionally
generates usage and help messages for you.</p>
<p>Here&#8217;s an example of using <tt class="docutils literal"><span class="pre">optparse</span></tt> in a simple script:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">optparse</span> <span class="kn">import</span> <span class="n">OptionParser</span>
<span class="p">[</span><span class="o">...</span><span class="p">]</span>
<span class="n">parser</span> <span class="o">=</span> <span class="n">OptionParser</span><span class="p">()</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s">&quot;-f&quot;</span><span class="p">,</span> <span class="s">&quot;--file&quot;</span><span class="p">,</span> <span class="n">dest</span><span class="o">=</span><span class="s">&quot;filename&quot;</span><span class="p">,</span>
                  <span class="n">help</span><span class="o">=</span><span class="s">&quot;write report to FILE&quot;</span><span class="p">,</span> <span class="n">metavar</span><span class="o">=</span><span class="s">&quot;FILE&quot;</span><span class="p">)</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s">&quot;-q&quot;</span><span class="p">,</span> <span class="s">&quot;--quiet&quot;</span><span class="p">,</span>
                  <span class="n">action</span><span class="o">=</span><span class="s">&quot;store_false&quot;</span><span class="p">,</span> <span class="n">dest</span><span class="o">=</span><span class="s">&quot;verbose&quot;</span><span class="p">,</span> <span class="n">default</span><span class="o">=</span><span class="bp">True</span><span class="p">,</span>
                  <span class="n">help</span><span class="o">=</span><span class="s">&quot;don&#39;t print status messages to stdout&quot;</span><span class="p">)</span>

<span class="p">(</span><span class="n">options</span><span class="p">,</span> <span class="n">args</span><span class="p">)</span> <span class="o">=</span> <span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">()</span>
</pre></div>
</div>
<p>With these few lines of code, users of your script can now do the &#8220;usual thing&#8221;
on the command-line, for example:</p>
<div class="highlight-python"><pre>&lt;yourscript&gt; --file=outfile -q</pre>
</div>
<p>As it parses the command line, <tt class="docutils literal"><span class="pre">optparse</span></tt> sets attributes of the <tt class="docutils literal"><span class="pre">options</span></tt>
object returned by <tt class="xref docutils literal"><span class="pre">parse_args()</span></tt> based on user-supplied command-line
values.  When <tt class="xref docutils literal"><span class="pre">parse_args()</span></tt> returns from parsing this command line,
<tt class="docutils literal"><span class="pre">options.filename</span></tt> will be <tt class="docutils literal"><span class="pre">&quot;outfile&quot;</span></tt> and <tt class="docutils literal"><span class="pre">options.verbose</span></tt> will be
<tt class="xref docutils literal"><span class="pre">False</span></tt>.  <tt class="docutils literal"><span class="pre">optparse</span></tt> supports both long and short options, allows short
options to be merged together, and allows options to be associated with their
arguments in a variety of ways.  Thus, the following command lines are all
equivalent to the above example:</p>
<div class="highlight-python"><pre>&lt;yourscript&gt; -f outfile --quiet
&lt;yourscript&gt; --quiet --file outfile
&lt;yourscript&gt; -q -foutfile
&lt;yourscript&gt; -qfoutfile</pre>
</div>
<p>Additionally, users can run one of</p>
<div class="highlight-python"><pre>&lt;yourscript&gt; -h
&lt;yourscript&gt; --help</pre>
</div>
<p>and <tt class="docutils literal"><span class="pre">optparse</span></tt> will print out a brief summary of your script&#8217;s options:</p>
<div class="highlight-python"><pre>usage: &lt;yourscript&gt; [options]

options:
  -h, --help            show this help message and exit
  -f FILE, --file=FILE  write report to FILE
  -q, --quiet           don't print status messages to stdout</pre>
</div>
<p>where the value of <em>yourscript</em> is determined at runtime (normally from
<tt class="docutils literal"><span class="pre">sys.argv[0]</span></tt>).</p>
<div class="section" id="background">
<span id="optparse-background"></span><h2>16.4.1. Background<a class="headerlink" href="#background" title="Permalink to this headline">¶</a></h2>
<p><tt class="xref docutils literal"><span class="pre">optparse</span></tt> was explicitly designed to encourage the creation of programs
with straightforward, conventional command-line interfaces.  To that end, it
supports only the most common command-line syntax and semantics conventionally
used under Unix.  If you are unfamiliar with these conventions, read this
section to acquaint yourself with them.</p>
<div class="section" id="terminology">
<span id="optparse-terminology"></span><h3>16.4.1.1. Terminology<a class="headerlink" href="#terminology" title="Permalink to this headline">¶</a></h3>
<dl class="docutils">
<dt>argument</dt>
<dd><p class="first">a string entered on the command-line, and passed by the shell to <tt class="docutils literal"><span class="pre">execl()</span></tt> or
<tt class="docutils literal"><span class="pre">execv()</span></tt>.  In Python, arguments are elements of <tt class="docutils literal"><span class="pre">sys.argv[1:]</span></tt>
(<tt class="docutils literal"><span class="pre">sys.argv[0]</span></tt> is the name of the program being executed).  Unix shells also
use the term &#8220;word&#8221;.</p>
<p class="last">It is occasionally desirable to substitute an argument list other than
<tt class="docutils literal"><span class="pre">sys.argv[1:]</span></tt>, so you should read &#8220;argument&#8221; as &#8220;an element of
<tt class="docutils literal"><span class="pre">sys.argv[1:]</span></tt>, or of some other list provided as a substitute for
<tt class="docutils literal"><span class="pre">sys.argv[1:]</span></tt>&#8220;.</p>
</dd>
<dt>option</dt>
<dd><p class="first">an argument used to supply extra information to guide or customize the execution
of a program.  There are many different syntaxes for options; the traditional
Unix syntax is a hyphen (&#8220;-&#8220;) followed by a single letter, e.g. <tt class="docutils literal"><span class="pre">&quot;-x&quot;</span></tt> or
<tt class="docutils literal"><span class="pre">&quot;-F&quot;</span></tt>.  Also, traditional Unix syntax allows multiple options to be merged
into a single argument, e.g.  <tt class="docutils literal"><span class="pre">&quot;-x</span> <span class="pre">-F&quot;</span></tt> is equivalent to <tt class="docutils literal"><span class="pre">&quot;-xF&quot;</span></tt>.  The GNU
project introduced <tt class="docutils literal"><span class="pre">&quot;--&quot;</span></tt> followed by a series of hyphen-separated words, e.g.
<tt class="docutils literal"><span class="pre">&quot;--file&quot;</span></tt> or <tt class="docutils literal"><span class="pre">&quot;--dry-run&quot;</span></tt>.  These are the only two option syntaxes
provided by <tt class="xref docutils literal"><span class="pre">optparse</span></tt>.</p>
<p>Some other option syntaxes that the world has seen include:</p>
<ul class="simple">
<li>a hyphen followed by a few letters, e.g. <tt class="docutils literal"><span class="pre">&quot;-pf&quot;</span></tt> (this is <em>not</em> the same
as multiple options merged into a single argument)</li>
<li>a hyphen followed by a whole word, e.g. <tt class="docutils literal"><span class="pre">&quot;-file&quot;</span></tt> (this is technically
equivalent to the previous syntax, but they aren&#8217;t usually seen in the same
program)</li>
<li>a plus sign followed by a single letter, or a few letters, or a word, e.g.
<tt class="docutils literal"><span class="pre">&quot;+f&quot;</span></tt>, <tt class="docutils literal"><span class="pre">&quot;+rgb&quot;</span></tt></li>
<li>a slash followed by a letter, or a few letters, or a word, e.g. <tt class="docutils literal"><span class="pre">&quot;/f&quot;</span></tt>,
<tt class="docutils literal"><span class="pre">&quot;/file&quot;</span></tt></li>
</ul>
<p class="last">These option syntaxes are not supported by <tt class="xref docutils literal"><span class="pre">optparse</span></tt>, and they never will
be.  This is deliberate: the first three are non-standard on any environment,
and the last only makes sense if you&#8217;re exclusively targeting VMS, MS-DOS,
and/or Windows.</p>
</dd>
<dt>option argument</dt>
<dd><p class="first">an argument that follows an option, is closely associated with that option, and
is consumed from the argument list when that option is. With <tt class="xref docutils literal"><span class="pre">optparse</span></tt>,
option arguments may either be in a separate argument from their option:</p>
<div class="highlight-python"><pre>-f foo
--file foo</pre>
</div>
<p>or included in the same argument:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="o">-</span><span class="n">ffoo</span>
<span class="o">--</span><span class="nb">file</span><span class="o">=</span><span class="n">foo</span>
</pre></div>
</div>
<p class="last">Typically, a given option either takes an argument or it doesn&#8217;t. Lots of people
want an &#8220;optional option arguments&#8221; feature, meaning that some options will take
an argument if they see it, and won&#8217;t if they don&#8217;t.  This is somewhat
controversial, because it makes parsing ambiguous: if <tt class="docutils literal"><span class="pre">&quot;-a&quot;</span></tt> takes an optional
argument and <tt class="docutils literal"><span class="pre">&quot;-b&quot;</span></tt> is another option entirely, how do we interpret <tt class="docutils literal"><span class="pre">&quot;-ab&quot;</span></tt>?
Because of this ambiguity, <tt class="xref docutils literal"><span class="pre">optparse</span></tt> does not support this feature.</p>
</dd>
<dt>positional argument</dt>
<dd>something leftover in the argument list after options have been parsed, i.e.
after options and their arguments have been parsed and removed from the argument
list.</dd>
<dt>required option</dt>
<dd>an option that must be supplied on the command-line; note that the phrase
&#8220;required option&#8221; is self-contradictory in English.  <tt class="xref docutils literal"><span class="pre">optparse</span></tt> doesn&#8217;t
prevent you from implementing required options, but doesn&#8217;t give you much help
at it either.  See <tt class="docutils literal"><span class="pre">examples/required_1.py</span></tt> and <tt class="docutils literal"><span class="pre">examples/required_2.py</span></tt> in
the <tt class="xref docutils literal"><span class="pre">optparse</span></tt> source distribution for two ways to implement required
options with <tt class="xref docutils literal"><span class="pre">optparse</span></tt>.</dd>
</dl>
<p>For example, consider this hypothetical command-line:</p>
<div class="highlight-python"><pre>prog -v --report /tmp/report.txt foo bar</pre>
</div>
<p><tt class="docutils literal"><span class="pre">&quot;-v&quot;</span></tt> and <tt class="docutils literal"><span class="pre">&quot;--report&quot;</span></tt> are both options.  Assuming that <em class="xref">--report</em>
takes one argument, <tt class="docutils literal"><span class="pre">&quot;/tmp/report.txt&quot;</span></tt> is an option argument.  <tt class="docutils literal"><span class="pre">&quot;foo&quot;</span></tt> and
<tt class="docutils literal"><span class="pre">&quot;bar&quot;</span></tt> are positional arguments.</p>
</div>
<div class="section" id="what-are-options-for">
<span id="optparse-what-options-for"></span><h3>16.4.1.2. What are options for?<a class="headerlink" href="#what-are-options-for" title="Permalink to this headline">¶</a></h3>
<p>Options are used to provide extra information to tune or customize the execution
of a program.  In case it wasn&#8217;t clear, options are usually <em>optional</em>.  A
program should be able to run just fine with no options whatsoever.  (Pick a
random program from the Unix or GNU toolsets.  Can it run without any options at
all and still make sense?  The main exceptions are <tt class="docutils literal"><span class="pre">find</span></tt>, <tt class="docutils literal"><span class="pre">tar</span></tt>, and
<tt class="docutils literal"><span class="pre">dd</span></tt>&#8212;all of which are mutant oddballs that have been rightly criticized
for their non-standard syntax and confusing interfaces.)</p>
<p>Lots of people want their programs to have &#8220;required options&#8221;.  Think about it.
If it&#8217;s required, then it&#8217;s <em>not optional</em>!  If there is a piece of information
that your program absolutely requires in order to run successfully, that&#8217;s what
positional arguments are for.</p>
<p>As an example of good command-line interface design, consider the humble <tt class="docutils literal"><span class="pre">cp</span></tt>
utility, for copying files.  It doesn&#8217;t make much sense to try to copy files
without supplying a destination and at least one source. Hence, <tt class="docutils literal"><span class="pre">cp</span></tt> fails if
you run it with no arguments.  However, it has a flexible, useful syntax that
does not require any options at all:</p>
<div class="highlight-python"><pre>cp SOURCE DEST
cp SOURCE ... DEST-DIR</pre>
</div>
<p>You can get pretty far with just that.  Most <tt class="docutils literal"><span class="pre">cp</span></tt> implementations provide a
bunch of options to tweak exactly how the files are copied: you can preserve
mode and modification time, avoid following symlinks, ask before clobbering
existing files, etc.  But none of this distracts from the core mission of
<tt class="docutils literal"><span class="pre">cp</span></tt>, which is to copy either one file to another, or several files to another
directory.</p>
</div>
<div class="section" id="what-are-positional-arguments-for">
<span id="optparse-what-positional-arguments-for"></span><h3>16.4.1.3. What are positional arguments for?<a class="headerlink" href="#what-are-positional-arguments-for" title="Permalink to this headline">¶</a></h3>
<p>Positional arguments are for those pieces of information that your program
absolutely, positively requires to run.</p>
<p>A good user interface should have as few absolute requirements as possible.  If
your program requires 17 distinct pieces of information in order to run
successfully, it doesn&#8217;t much matter <em>how</em> you get that information from the
user&#8212;most people will give up and walk away before they successfully run the
program.  This applies whether the user interface is a command-line, a
configuration file, or a GUI: if you make that many demands on your users, most
of them will simply give up.</p>
<p>In short, try to minimize the amount of information that users are absolutely
required to supply&#8212;use sensible defaults whenever possible.  Of course, you
also want to make your programs reasonably flexible.  That&#8217;s what options are
for.  Again, it doesn&#8217;t matter if they are entries in a config file, widgets in
the &#8220;Preferences&#8221; dialog of a GUI, or command-line options&#8212;the more options
you implement, the more flexible your program is, and the more complicated its
implementation becomes.  Too much flexibility has drawbacks as well, of course;
too many options can overwhelm users and make your code much harder to maintain.</p>
</div>
</div>
<div class="section" id="tutorial">
<span id="optparse-tutorial"></span><h2>16.4.2. Tutorial<a class="headerlink" href="#tutorial" title="Permalink to this headline">¶</a></h2>
<p>While <tt class="xref docutils literal"><span class="pre">optparse</span></tt> is quite flexible and powerful, it&#8217;s also straightforward
to use in most cases.  This section covers the code patterns that are common to
any <tt class="xref docutils literal"><span class="pre">optparse</span></tt>-based program.</p>
<p>First, you need to import the OptionParser class; then, early in the main
program, create an OptionParser instance:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">optparse</span> <span class="kn">import</span> <span class="n">OptionParser</span>
<span class="p">[</span><span class="o">...</span><span class="p">]</span>
<span class="n">parser</span> <span class="o">=</span> <span class="n">OptionParser</span><span class="p">()</span>
</pre></div>
</div>
<p>Then you can start defining options.  The basic syntax is:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="n">opt_str</span><span class="p">,</span> <span class="o">...</span><span class="p">,</span>
                  <span class="n">attr</span><span class="o">=</span><span class="n">value</span><span class="p">,</span> <span class="o">...</span><span class="p">)</span>
</pre></div>
</div>
<p>Each option has one or more option strings, such as <tt class="docutils literal"><span class="pre">&quot;-f&quot;</span></tt> or <tt class="docutils literal"><span class="pre">&quot;--file&quot;</span></tt>,
and several option attributes that tell <tt class="xref docutils literal"><span class="pre">optparse</span></tt> what to expect and what
to do when it encounters that option on the command line.</p>
<p>Typically, each option will have one short option string and one long option
string, e.g.:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s">&quot;-f&quot;</span><span class="p">,</span> <span class="s">&quot;--file&quot;</span><span class="p">,</span> <span class="o">...</span><span class="p">)</span>
</pre></div>
</div>
<p>You&#8217;re free to define as many short option strings and as many long option
strings as you like (including zero), as long as there is at least one option
string overall.</p>
<p>The option strings passed to <tt class="xref docutils literal"><span class="pre">add_option()</span></tt> are effectively labels for the
option defined by that call.  For brevity, we will frequently refer to
<em>encountering an option</em> on the command line; in reality, <tt class="xref docutils literal"><span class="pre">optparse</span></tt>
encounters <em>option strings</em> and looks up options from them.</p>
<p>Once all of your options are defined, instruct <tt class="xref docutils literal"><span class="pre">optparse</span></tt> to parse your
program&#8217;s command line:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="p">(</span><span class="n">options</span><span class="p">,</span> <span class="n">args</span><span class="p">)</span> <span class="o">=</span> <span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">()</span>
</pre></div>
</div>
<p>(If you like, you can pass a custom argument list to <tt class="xref docutils literal"><span class="pre">parse_args()</span></tt>, but
that&#8217;s rarely necessary: by default it uses <tt class="docutils literal"><span class="pre">sys.argv[1:]</span></tt>.)</p>
<p><tt class="xref docutils literal"><span class="pre">parse_args()</span></tt> returns two values:</p>
<ul class="simple">
<li><tt class="docutils literal"><span class="pre">options</span></tt>, an object containing values for all of your options&#8212;e.g. if
<tt class="docutils literal"><span class="pre">&quot;--file&quot;</span></tt> takes a single string argument, then <tt class="docutils literal"><span class="pre">options.file</span></tt> will be the
filename supplied by the user, or <tt class="xref docutils literal"><span class="pre">None</span></tt> if the user did not supply that
option</li>
<li><tt class="docutils literal"><span class="pre">args</span></tt>, the list of positional arguments leftover after parsing options</li>
</ul>
<p>This tutorial section only covers the four most important option attributes:
<tt class="xref docutils literal"><span class="pre">action</span></tt>, <a title="type" class="reference external" href="functions.html#type"><tt class="xref docutils literal"><span class="pre">type</span></tt></a>, <tt class="xref docutils literal"><span class="pre">dest</span></tt> (destination), and <a title="help" class="reference external" href="functions.html#help"><tt class="xref docutils literal"><span class="pre">help</span></tt></a>. Of
these, <tt class="xref docutils literal"><span class="pre">action</span></tt> is the most fundamental.</p>
<div class="section" id="understanding-option-actions">
<span id="optparse-understanding-option-actions"></span><h3>16.4.2.1. Understanding option actions<a class="headerlink" href="#understanding-option-actions" title="Permalink to this headline">¶</a></h3>
<p>Actions tell <tt class="xref docutils literal"><span class="pre">optparse</span></tt> what to do when it encounters an option on the
command line.  There is a fixed set of actions hard-coded into <tt class="xref docutils literal"><span class="pre">optparse</span></tt>;
adding new actions is an advanced topic covered in section
<a class="reference internal" href="#optparse-extending-optparse"><em>Extending optparse</em></a>. Most actions tell
<tt class="xref docutils literal"><span class="pre">optparse</span></tt> to store a value in some variable&#8212;for example, take a string
from the command line and store it in an attribute of <tt class="docutils literal"><span class="pre">options</span></tt>.</p>
<p>If you don&#8217;t specify an option action, <tt class="xref docutils literal"><span class="pre">optparse</span></tt> defaults to <tt class="docutils literal"><span class="pre">store</span></tt>.</p>
</div>
<div class="section" id="the-store-action">
<span id="optparse-store-action"></span><h3>16.4.2.2. The store action<a class="headerlink" href="#the-store-action" title="Permalink to this headline">¶</a></h3>
<p>The most common option action is <tt class="docutils literal"><span class="pre">store</span></tt>, which tells <tt class="xref docutils literal"><span class="pre">optparse</span></tt> to take
the next argument (or the remainder of the current argument), ensure that it is
of the correct type, and store it to your chosen destination.</p>
<p>For example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s">&quot;-f&quot;</span><span class="p">,</span> <span class="s">&quot;--file&quot;</span><span class="p">,</span>
                  <span class="n">action</span><span class="o">=</span><span class="s">&quot;store&quot;</span><span class="p">,</span> <span class="nb">type</span><span class="o">=</span><span class="s">&quot;string&quot;</span><span class="p">,</span> <span class="n">dest</span><span class="o">=</span><span class="s">&quot;filename&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>Now let&#8217;s make up a fake command line and ask <tt class="xref docutils literal"><span class="pre">optparse</span></tt> to parse it:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">args</span> <span class="o">=</span> <span class="p">[</span><span class="s">&quot;-f&quot;</span><span class="p">,</span> <span class="s">&quot;foo.txt&quot;</span><span class="p">]</span>
<span class="p">(</span><span class="n">options</span><span class="p">,</span> <span class="n">args</span><span class="p">)</span> <span class="o">=</span> <span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">(</span><span class="n">args</span><span class="p">)</span>
</pre></div>
</div>
<p>When <tt class="xref docutils literal"><span class="pre">optparse</span></tt> sees the option string <tt class="docutils literal"><span class="pre">&quot;-f&quot;</span></tt>, it consumes the next
argument, <tt class="docutils literal"><span class="pre">&quot;foo.txt&quot;</span></tt>, and stores it in <tt class="docutils literal"><span class="pre">options.filename</span></tt>.  So, after this
call to <tt class="xref docutils literal"><span class="pre">parse_args()</span></tt>, <tt class="docutils literal"><span class="pre">options.filename</span></tt> is <tt class="docutils literal"><span class="pre">&quot;foo.txt&quot;</span></tt>.</p>
<p>Some other option types supported by <tt class="xref docutils literal"><span class="pre">optparse</span></tt> are <tt class="docutils literal"><span class="pre">int</span></tt> and <tt class="docutils literal"><span class="pre">float</span></tt>.
Here&#8217;s an option that expects an integer argument:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s">&quot;-n&quot;</span><span class="p">,</span> <span class="nb">type</span><span class="o">=</span><span class="s">&quot;int&quot;</span><span class="p">,</span> <span class="n">dest</span><span class="o">=</span><span class="s">&quot;num&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>Note that this option has no long option string, which is perfectly acceptable.
Also, there&#8217;s no explicit action, since the default is <tt class="docutils literal"><span class="pre">store</span></tt>.</p>
<p>Let&#8217;s parse another fake command-line.  This time, we&#8217;ll jam the option argument
right up against the option: since <tt class="docutils literal"><span class="pre">&quot;-n42&quot;</span></tt> (one argument) is equivalent to
<tt class="docutils literal"><span class="pre">&quot;-n</span> <span class="pre">42&quot;</span></tt> (two arguments), the code</p>
<div class="highlight-python"><div class="highlight"><pre><span class="p">(</span><span class="n">options</span><span class="p">,</span> <span class="n">args</span><span class="p">)</span> <span class="o">=</span> <span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s">&quot;-n42&quot;</span><span class="p">])</span>
<span class="k">print</span> <span class="n">options</span><span class="o">.</span><span class="n">num</span>
</pre></div>
</div>
<p>will print <tt class="docutils literal"><span class="pre">&quot;42&quot;</span></tt>.</p>
<p>If you don&#8217;t specify a type, <tt class="xref docutils literal"><span class="pre">optparse</span></tt> assumes <tt class="docutils literal"><span class="pre">string</span></tt>.  Combined with
the fact that the default action is <tt class="docutils literal"><span class="pre">store</span></tt>, that means our first example can
be a lot shorter:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s">&quot;-f&quot;</span><span class="p">,</span> <span class="s">&quot;--file&quot;</span><span class="p">,</span> <span class="n">dest</span><span class="o">=</span><span class="s">&quot;filename&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>If you don&#8217;t supply a destination, <tt class="xref docutils literal"><span class="pre">optparse</span></tt> figures out a sensible
default from the option strings: if the first long option string is
<tt class="docutils literal"><span class="pre">&quot;--foo-bar&quot;</span></tt>, then the default destination is <tt class="docutils literal"><span class="pre">foo_bar</span></tt>.  If there are no
long option strings, <tt class="xref docutils literal"><span class="pre">optparse</span></tt> looks at the first short option string: the
default destination for <tt class="docutils literal"><span class="pre">&quot;-f&quot;</span></tt> is <tt class="docutils literal"><span class="pre">f</span></tt>.</p>
<p><tt class="xref docutils literal"><span class="pre">optparse</span></tt> also includes built-in <tt class="docutils literal"><span class="pre">long</span></tt> and <tt class="docutils literal"><span class="pre">complex</span></tt> types.  Adding
types is covered in section <a class="reference internal" href="#optparse-extending-optparse"><em>Extending optparse</em></a>.</p>
</div>
<div class="section" id="handling-boolean-flag-options">
<span id="optparse-handling-boolean-options"></span><h3>16.4.2.3. Handling boolean (flag) options<a class="headerlink" href="#handling-boolean-flag-options" title="Permalink to this headline">¶</a></h3>
<p>Flag options&#8212;set a variable to true or false when a particular option is seen
&#8212;are quite common.  <tt class="xref docutils literal"><span class="pre">optparse</span></tt> supports them with two separate actions,
<tt class="docutils literal"><span class="pre">store_true</span></tt> and <tt class="docutils literal"><span class="pre">store_false</span></tt>.  For example, you might have a <tt class="docutils literal"><span class="pre">verbose</span></tt>
flag that is turned on with <tt class="docutils literal"><span class="pre">&quot;-v&quot;</span></tt> and off with <tt class="docutils literal"><span class="pre">&quot;-q&quot;</span></tt>:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s">&quot;-v&quot;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s">&quot;store_true&quot;</span><span class="p">,</span> <span class="n">dest</span><span class="o">=</span><span class="s">&quot;verbose&quot;</span><span class="p">)</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s">&quot;-q&quot;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s">&quot;store_false&quot;</span><span class="p">,</span> <span class="n">dest</span><span class="o">=</span><span class="s">&quot;verbose&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>Here we have two different options with the same destination, which is perfectly
OK.  (It just means you have to be a bit careful when setting default values&#8212;
see below.)</p>
<p>When <tt class="xref docutils literal"><span class="pre">optparse</span></tt> encounters <tt class="docutils literal"><span class="pre">&quot;-v&quot;</span></tt> on the command line, it sets
<tt class="docutils literal"><span class="pre">options.verbose</span></tt> to <tt class="xref docutils literal"><span class="pre">True</span></tt>; when it encounters <tt class="docutils literal"><span class="pre">&quot;-q&quot;</span></tt>,
<tt class="docutils literal"><span class="pre">options.verbose</span></tt> is set to <tt class="xref docutils literal"><span class="pre">False</span></tt>.</p>
</div>
<div class="section" id="other-actions">
<span id="optparse-other-actions"></span><h3>16.4.2.4. Other actions<a class="headerlink" href="#other-actions" title="Permalink to this headline">¶</a></h3>
<p>Some other actions supported by <tt class="xref docutils literal"><span class="pre">optparse</span></tt> are:</p>
<dl class="docutils">
<dt><tt class="docutils literal"><span class="pre">store_const</span></tt></dt>
<dd>store a constant value</dd>
<dt><tt class="docutils literal"><span class="pre">append</span></tt></dt>
<dd>append this option&#8217;s argument to a list</dd>
<dt><tt class="docutils literal"><span class="pre">count</span></tt></dt>
<dd>increment a counter by one</dd>
<dt><tt class="docutils literal"><span class="pre">callback</span></tt></dt>
<dd>call a specified function</dd>
</dl>
<p>These are covered in section <a class="reference internal" href="#optparse-reference-guide"><em>Reference Guide</em></a>, Reference Guide
and section <a class="reference internal" href="#optparse-option-callbacks"><em>Option Callbacks</em></a>.</p>
</div>
<div class="section" id="default-values">
<span id="optparse-default-values"></span><h3>16.4.2.5. Default values<a class="headerlink" href="#default-values" title="Permalink to this headline">¶</a></h3>
<p>All of the above examples involve setting some variable (the &#8220;destination&#8221;) when
certain command-line options are seen.  What happens if those options are never
seen?  Since we didn&#8217;t supply any defaults, they are all set to <tt class="xref docutils literal"><span class="pre">None</span></tt>.  This
is usually fine, but sometimes you want more control.  <tt class="xref docutils literal"><span class="pre">optparse</span></tt> lets you
supply a default value for each destination, which is assigned before the
command line is parsed.</p>
<p>First, consider the verbose/quiet example.  If we want <tt class="xref docutils literal"><span class="pre">optparse</span></tt> to set
<tt class="docutils literal"><span class="pre">verbose</span></tt> to <tt class="xref docutils literal"><span class="pre">True</span></tt> unless <tt class="docutils literal"><span class="pre">&quot;-q&quot;</span></tt> is seen, then we can do this:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s">&quot;-v&quot;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s">&quot;store_true&quot;</span><span class="p">,</span> <span class="n">dest</span><span class="o">=</span><span class="s">&quot;verbose&quot;</span><span class="p">,</span> <span class="n">default</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s">&quot;-q&quot;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s">&quot;store_false&quot;</span><span class="p">,</span> <span class="n">dest</span><span class="o">=</span><span class="s">&quot;verbose&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>Since default values apply to the <em>destination</em> rather than to any particular
option, and these two options happen to have the same destination, this is
exactly equivalent:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s">&quot;-v&quot;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s">&quot;store_true&quot;</span><span class="p">,</span> <span class="n">dest</span><span class="o">=</span><span class="s">&quot;verbose&quot;</span><span class="p">)</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s">&quot;-q&quot;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s">&quot;store_false&quot;</span><span class="p">,</span> <span class="n">dest</span><span class="o">=</span><span class="s">&quot;verbose&quot;</span><span class="p">,</span> <span class="n">default</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
</pre></div>
</div>
<p>Consider this:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s">&quot;-v&quot;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s">&quot;store_true&quot;</span><span class="p">,</span> <span class="n">dest</span><span class="o">=</span><span class="s">&quot;verbose&quot;</span><span class="p">,</span> <span class="n">default</span><span class="o">=</span><span class="bp">False</span><span class="p">)</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s">&quot;-q&quot;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s">&quot;store_false&quot;</span><span class="p">,</span> <span class="n">dest</span><span class="o">=</span><span class="s">&quot;verbose&quot;</span><span class="p">,</span> <span class="n">default</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
</pre></div>
</div>
<p>Again, the default value for <tt class="docutils literal"><span class="pre">verbose</span></tt> will be <tt class="xref docutils literal"><span class="pre">True</span></tt>: the last default
value supplied for any particular destination is the one that counts.</p>
<p>A clearer way to specify default values is the <tt class="xref docutils literal"><span class="pre">set_defaults()</span></tt> method of
OptionParser, which you can call at any time before calling <tt class="xref docutils literal"><span class="pre">parse_args()</span></tt>:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">parser</span><span class="o">.</span><span class="n">set_defaults</span><span class="p">(</span><span class="n">verbose</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="o">...</span><span class="p">)</span>
<span class="p">(</span><span class="n">options</span><span class="p">,</span> <span class="n">args</span><span class="p">)</span> <span class="o">=</span> <span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">()</span>
</pre></div>
</div>
<p>As before, the last value specified for a given option destination is the one
that counts.  For clarity, try to use one method or the other of setting default
values, not both.</p>
</div>
<div class="section" id="generating-help">
<span id="optparse-generating-help"></span><h3>16.4.2.6. Generating help<a class="headerlink" href="#generating-help" title="Permalink to this headline">¶</a></h3>
<p><tt class="xref docutils literal"><span class="pre">optparse</span></tt>&#8216;s ability to generate help and usage text automatically is
useful for creating user-friendly command-line interfaces.  All you have to do
is supply a <a title="help" class="reference external" href="functions.html#help"><tt class="xref docutils literal"><span class="pre">help</span></tt></a> value for each option, and optionally a short usage
message for your whole program.  Here&#8217;s an OptionParser populated with
user-friendly (documented) options:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">usage</span> <span class="o">=</span> <span class="s">&quot;usage: %prog [options] arg1 arg2&quot;</span>
<span class="n">parser</span> <span class="o">=</span> <span class="n">OptionParser</span><span class="p">(</span><span class="n">usage</span><span class="o">=</span><span class="n">usage</span><span class="p">)</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s">&quot;-v&quot;</span><span class="p">,</span> <span class="s">&quot;--verbose&quot;</span><span class="p">,</span>
                  <span class="n">action</span><span class="o">=</span><span class="s">&quot;store_true&quot;</span><span class="p">,</span> <span class="n">dest</span><span class="o">=</span><span class="s">&quot;verbose&quot;</span><span class="p">,</span> <span class="n">default</span><span class="o">=</span><span class="bp">True</span><span class="p">,</span>
                  <span class="n">help</span><span class="o">=</span><span class="s">&quot;make lots of noise [default]&quot;</span><span class="p">)</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s">&quot;-q&quot;</span><span class="p">,</span> <span class="s">&quot;--quiet&quot;</span><span class="p">,</span>
                  <span class="n">action</span><span class="o">=</span><span class="s">&quot;store_false&quot;</span><span class="p">,</span> <span class="n">dest</span><span class="o">=</span><span class="s">&quot;verbose&quot;</span><span class="p">,</span>
                  <span class="n">help</span><span class="o">=</span><span class="s">&quot;be vewwy quiet (I&#39;m hunting wabbits)&quot;</span><span class="p">)</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s">&quot;-f&quot;</span><span class="p">,</span> <span class="s">&quot;--filename&quot;</span><span class="p">,</span>
                  <span class="n">metavar</span><span class="o">=</span><span class="s">&quot;FILE&quot;</span><span class="p">,</span> <span class="n">help</span><span class="o">=</span><span class="s">&quot;write output to FILE&quot;</span><span class="p">),</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s">&quot;-m&quot;</span><span class="p">,</span> <span class="s">&quot;--mode&quot;</span><span class="p">,</span>
                  <span class="n">default</span><span class="o">=</span><span class="s">&quot;intermediate&quot;</span><span class="p">,</span>
                  <span class="n">help</span><span class="o">=</span><span class="s">&quot;interaction mode: novice, intermediate, &quot;</span>
                       <span class="s">&quot;or expert [default: </span><span class="si">%d</span><span class="s">efault]&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>If <tt class="xref docutils literal"><span class="pre">optparse</span></tt> encounters either <tt class="docutils literal"><span class="pre">&quot;-h&quot;</span></tt> or <tt class="docutils literal"><span class="pre">&quot;--help&quot;</span></tt> on the
command-line, or if you just call <tt class="xref docutils literal"><span class="pre">parser.print_help()</span></tt>, it prints the
following to standard output:</p>
<div class="highlight-python"><pre>usage: &lt;yourscript&gt; [options] arg1 arg2

options:
  -h, --help            show this help message and exit
  -v, --verbose         make lots of noise [default]
  -q, --quiet           be vewwy quiet (I'm hunting wabbits)
  -f FILE, --filename=FILE
                        write output to FILE
  -m MODE, --mode=MODE  interaction mode: novice, intermediate, or
                        expert [default: intermediate]</pre>
</div>
<p>(If the help output is triggered by a help option, <tt class="xref docutils literal"><span class="pre">optparse</span></tt> exits after
printing the help text.)</p>
<p>There&#8217;s a lot going on here to help <tt class="xref docutils literal"><span class="pre">optparse</span></tt> generate the best possible
help message:</p>
<ul>
<li><p class="first">the script defines its own usage message:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">usage</span> <span class="o">=</span> <span class="s">&quot;usage: %prog [options] arg1 arg2&quot;</span>
</pre></div>
</div>
<p><tt class="xref docutils literal"><span class="pre">optparse</span></tt> expands <tt class="docutils literal"><span class="pre">&quot;%prog&quot;</span></tt> in the usage string to the name of the
current program, i.e. <tt class="docutils literal"><span class="pre">os.path.basename(sys.argv[0])</span></tt>.  The expanded string is
then printed before the detailed option help.</p>
<p>If you don&#8217;t supply a usage string, <tt class="xref docutils literal"><span class="pre">optparse</span></tt> uses a bland but sensible
default: <tt class="docutils literal"><span class="pre">&quot;usage:</span> <span class="pre">%prog</span> <span class="pre">[options]&quot;</span></tt>, which is fine if your script doesn&#8217;t take
any positional arguments.</p>
</li>
<li><p class="first">every option defines a help string, and doesn&#8217;t worry about line-wrapping&#8212;
<tt class="xref docutils literal"><span class="pre">optparse</span></tt> takes care of wrapping lines and making the help output look
good.</p>
</li>
<li><p class="first">options that take a value indicate this fact in their automatically-generated
help message, e.g. for the &#8220;mode&#8221; option:</p>
<div class="highlight-python"><pre>-m MODE, --mode=MODE</pre>
</div>
<p>Here, &#8220;MODE&#8221; is called the meta-variable: it stands for the argument that the
user is expected to supply to <a class="reference external" href="../using/cmdline.html#cmdoption-m"><em class="xref">-m</em></a>/<em class="xref">--mode</em>.  By default,
<tt class="xref docutils literal"><span class="pre">optparse</span></tt> converts the destination variable name to uppercase and uses
that for the meta-variable.  Sometimes, that&#8217;s not what you want&#8212;for example,
the <em class="xref">--filename</em> option explicitly sets <tt class="docutils literal"><span class="pre">metavar=&quot;FILE&quot;</span></tt>, resulting in
this automatically-generated option description:</p>
<div class="highlight-python"><pre>-f FILE, --filename=FILE</pre>
</div>
<p>This is important for more than just saving space, though: the manually written
help text uses the meta-variable &#8220;FILE&#8221; to clue the user in that there&#8217;s a
connection between the semi-formal syntax &#8220;-f FILE&#8221; and the informal semantic
description &#8220;write output to FILE&#8221;. This is a simple but effective way to make
your help text a lot clearer and more useful for end users.</p>
</li>
</ul>
<p>
<span class="versionmodified">New in version 2.4: </span>Options that have a default value can include <tt class="docutils literal"><span class="pre">%default</span></tt> in the help
string&#8212;<tt class="xref docutils literal"><span class="pre">optparse</span></tt> will replace it with <a title="str" class="reference external" href="functions.html#str"><tt class="xref docutils literal"><span class="pre">str()</span></tt></a> of the option&#8217;s
default value.  If an option has no default value (or the default value is
<tt class="xref docutils literal"><span class="pre">None</span></tt>), <tt class="docutils literal"><span class="pre">%default</span></tt> expands to <tt class="docutils literal"><span class="pre">none</span></tt>.</p>
<p>When dealing with many options, it is convenient to group these
options for better help output.  An <tt class="xref docutils literal"><span class="pre">OptionParser</span></tt> can contain
several option groups, each of which can contain several options.</p>
<p>Continuing with the parser defined above, adding an
<tt class="xref docutils literal"><span class="pre">OptionGroup</span></tt> to a parser is easy:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">group</span> <span class="o">=</span> <span class="n">OptionGroup</span><span class="p">(</span><span class="n">parser</span><span class="p">,</span> <span class="s">&quot;Dangerous Options&quot;</span><span class="p">,</span>
                    <span class="s">&quot;Caution: use these options at your own risk.  &quot;</span>
                    <span class="s">&quot;It is believed that some of them bite.&quot;</span><span class="p">)</span>
<span class="n">group</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s">&quot;-g&quot;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s">&quot;store_true&quot;</span><span class="p">,</span> <span class="n">help</span><span class="o">=</span><span class="s">&quot;Group option.&quot;</span><span class="p">)</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_option_group</span><span class="p">(</span><span class="n">group</span><span class="p">)</span>
</pre></div>
</div>
<p>This would result in the following help output:</p>
<div class="highlight-python"><pre>usage:  [options] arg1 arg2

options:
  -h, --help           show this help message and exit
  -v, --verbose        make lots of noise [default]
  -q, --quiet          be vewwy quiet (I'm hunting wabbits)
  -fFILE, --file=FILE  write output to FILE
  -mMODE, --mode=MODE  interaction mode: one of 'novice', 'intermediate'
                       [default], 'expert'

  Dangerous Options:
  Caution: use of these options is at your own risk.  It is believed that
  some of them bite.
  -g                 Group option.</pre>
</div>
</div>
<div class="section" id="printing-a-version-string">
<span id="optparse-printing-version-string"></span><h3>16.4.2.7. Printing a version string<a class="headerlink" href="#printing-a-version-string" title="Permalink to this headline">¶</a></h3>
<p>Similar to the brief usage string, <tt class="xref docutils literal"><span class="pre">optparse</span></tt> can also print a version
string for your program.  You have to supply the string as the <tt class="docutils literal"><span class="pre">version</span></tt>
argument to OptionParser:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">parser</span> <span class="o">=</span> <span class="n">OptionParser</span><span class="p">(</span><span class="n">usage</span><span class="o">=</span><span class="s">&quot;%prog [-f] [-q]&quot;</span><span class="p">,</span> <span class="n">version</span><span class="o">=</span><span class="s">&quot;%prog 1.0&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p><tt class="docutils literal"><span class="pre">&quot;%prog&quot;</span></tt> is expanded just like it is in <tt class="docutils literal"><span class="pre">usage</span></tt>.  Apart from that,
<tt class="docutils literal"><span class="pre">version</span></tt> can contain anything you like.  When you supply it, <tt class="xref docutils literal"><span class="pre">optparse</span></tt>
automatically adds a <tt class="docutils literal"><span class="pre">&quot;--version&quot;</span></tt> option to your parser. If it encounters
this option on the command line, it expands your <tt class="docutils literal"><span class="pre">version</span></tt> string (by
replacing <tt class="docutils literal"><span class="pre">&quot;%prog&quot;</span></tt>), prints it to stdout, and exits.</p>
<p>For example, if your script is called <tt class="docutils literal"><span class="pre">/usr/bin/foo</span></tt>:</p>
<div class="highlight-python"><pre>$ /usr/bin/foo --version
foo 1.0</pre>
</div>
</div>
<div class="section" id="how-optparse-handles-errors">
<span id="optparse-how-optparse-handles-errors"></span><h3>16.4.2.8. How <tt class="xref docutils literal"><span class="pre">optparse</span></tt> handles errors<a class="headerlink" href="#how-optparse-handles-errors" title="Permalink to this headline">¶</a></h3>
<p>There are two broad classes of errors that <tt class="xref docutils literal"><span class="pre">optparse</span></tt> has to worry about:
programmer errors and user errors.  Programmer errors are usually erroneous
calls to <tt class="docutils literal"><span class="pre">parser.add_option()</span></tt>, e.g. invalid option strings, unknown option
attributes, missing option attributes, etc.  These are dealt with in the usual
way: raise an exception (either <tt class="docutils literal"><span class="pre">optparse.OptionError</span></tt> or <a title="exceptions.TypeError" class="reference external" href="exceptions.html#exceptions.TypeError"><tt class="xref docutils literal"><span class="pre">TypeError</span></tt></a>) and
let the program crash.</p>
<p>Handling user errors is much more important, since they are guaranteed to happen
no matter how stable your code is.  <tt class="xref docutils literal"><span class="pre">optparse</span></tt> can automatically detect
some user errors, such as bad option arguments (passing <tt class="docutils literal"><span class="pre">&quot;-n</span> <span class="pre">4x&quot;</span></tt> where
<em class="xref">-n</em> takes an integer argument), missing arguments (<tt class="docutils literal"><span class="pre">&quot;-n&quot;</span></tt> at the end
of the command line, where <em class="xref">-n</em> takes an argument of any type).  Also,
you can call <tt class="docutils literal"><span class="pre">parser.error()</span></tt> to signal an application-defined error
condition:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="p">(</span><span class="n">options</span><span class="p">,</span> <span class="n">args</span><span class="p">)</span> <span class="o">=</span> <span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">()</span>
<span class="p">[</span><span class="o">...</span><span class="p">]</span>
<span class="k">if</span> <span class="n">options</span><span class="o">.</span><span class="n">a</span> <span class="ow">and</span> <span class="n">options</span><span class="o">.</span><span class="n">b</span><span class="p">:</span>
    <span class="n">parser</span><span class="o">.</span><span class="n">error</span><span class="p">(</span><span class="s">&quot;options -a and -b are mutually exclusive&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>In either case, <tt class="xref docutils literal"><span class="pre">optparse</span></tt> handles the error the same way: it prints the
program&#8217;s usage message and an error message to standard error and exits with
error status 2.</p>
<p>Consider the first example above, where the user passes <tt class="docutils literal"><span class="pre">&quot;4x&quot;</span></tt> to an option
that takes an integer:</p>
<div class="highlight-python"><pre>$ /usr/bin/foo -n 4x
usage: foo [options]

foo: error: option -n: invalid integer value: '4x'</pre>
</div>
<p>Or, where the user fails to pass a value at all:</p>
<div class="highlight-python"><pre>$ /usr/bin/foo -n
usage: foo [options]

foo: error: -n option requires an argument</pre>
</div>
<p><tt class="xref docutils literal"><span class="pre">optparse</span></tt>-generated error messages take care always to mention the
option involved in the error; be sure to do the same when calling
<tt class="docutils literal"><span class="pre">parser.error()</span></tt> from your application code.</p>
<p>If <tt class="xref docutils literal"><span class="pre">optparse</span></tt>&#8216;s default error-handling behaviour does not suit your needs,
you&#8217;ll need to subclass OptionParser and override its <a title="exit" class="reference external" href="constants.html#exit"><tt class="xref docutils literal"><span class="pre">exit()</span></tt></a> and/or
<tt class="xref docutils literal"><span class="pre">error()</span></tt> methods.</p>
</div>
<div class="section" id="putting-it-all-together">
<span id="optparse-putting-it-all-together"></span><h3>16.4.2.9. Putting it all together<a class="headerlink" href="#putting-it-all-together" title="Permalink to this headline">¶</a></h3>
<p>Here&#8217;s what <tt class="xref docutils literal"><span class="pre">optparse</span></tt>-based scripts usually look like:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">optparse</span> <span class="kn">import</span> <span class="n">OptionParser</span>
<span class="p">[</span><span class="o">...</span><span class="p">]</span>
<span class="k">def</span> <span class="nf">main</span><span class="p">():</span>
    <span class="n">usage</span> <span class="o">=</span> <span class="s">&quot;usage: %prog [options] arg&quot;</span>
    <span class="n">parser</span> <span class="o">=</span> <span class="n">OptionParser</span><span class="p">(</span><span class="n">usage</span><span class="p">)</span>
    <span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s">&quot;-f&quot;</span><span class="p">,</span> <span class="s">&quot;--file&quot;</span><span class="p">,</span> <span class="n">dest</span><span class="o">=</span><span class="s">&quot;filename&quot;</span><span class="p">,</span>
                      <span class="n">help</span><span class="o">=</span><span class="s">&quot;read data from FILENAME&quot;</span><span class="p">)</span>
    <span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s">&quot;-v&quot;</span><span class="p">,</span> <span class="s">&quot;--verbose&quot;</span><span class="p">,</span>
                      <span class="n">action</span><span class="o">=</span><span class="s">&quot;store_true&quot;</span><span class="p">,</span> <span class="n">dest</span><span class="o">=</span><span class="s">&quot;verbose&quot;</span><span class="p">)</span>
    <span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s">&quot;-q&quot;</span><span class="p">,</span> <span class="s">&quot;--quiet&quot;</span><span class="p">,</span>
                      <span class="n">action</span><span class="o">=</span><span class="s">&quot;store_false&quot;</span><span class="p">,</span> <span class="n">dest</span><span class="o">=</span><span class="s">&quot;verbose&quot;</span><span class="p">)</span>
    <span class="p">[</span><span class="o">...</span><span class="p">]</span>
    <span class="p">(</span><span class="n">options</span><span class="p">,</span> <span class="n">args</span><span class="p">)</span> <span class="o">=</span> <span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">()</span>
    <span class="k">if</span> <span class="nb">len</span><span class="p">(</span><span class="n">args</span><span class="p">)</span> <span class="o">!=</span> <span class="mf">1</span><span class="p">:</span>
        <span class="n">parser</span><span class="o">.</span><span class="n">error</span><span class="p">(</span><span class="s">&quot;incorrect number of arguments&quot;</span><span class="p">)</span>
    <span class="k">if</span> <span class="n">options</span><span class="o">.</span><span class="n">verbose</span><span class="p">:</span>
        <span class="k">print</span> <span class="s">&quot;reading </span><span class="si">%s</span><span class="s">...&quot;</span> <span class="o">%</span> <span class="n">options</span><span class="o">.</span><span class="n">filename</span>
    <span class="p">[</span><span class="o">...</span><span class="p">]</span>

<span class="k">if</span> <span class="n">__name__</span> <span class="o">==</span> <span class="s">&quot;__main__&quot;</span><span class="p">:</span>
    <span class="n">main</span><span class="p">()</span>
</pre></div>
</div>
</div>
</div>
<div class="section" id="reference-guide">
<span id="optparse-reference-guide"></span><h2>16.4.3. Reference Guide<a class="headerlink" href="#reference-guide" title="Permalink to this headline">¶</a></h2>
<div class="section" id="creating-the-parser">
<span id="optparse-creating-parser"></span><h3>16.4.3.1. Creating the parser<a class="headerlink" href="#creating-the-parser" title="Permalink to this headline">¶</a></h3>
<p>The first step in using <tt class="xref docutils literal"><span class="pre">optparse</span></tt> is to create an OptionParser instance:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">parser</span> <span class="o">=</span> <span class="n">OptionParser</span><span class="p">(</span><span class="o">...</span><span class="p">)</span>
</pre></div>
</div>
<p>The OptionParser constructor has no required arguments, but a number of optional
keyword arguments.  You should always pass them as keyword arguments, i.e. do
not rely on the order in which the arguments are declared.</p>
<blockquote>
<dl class="docutils">
<dt><tt class="docutils literal"><span class="pre">usage</span></tt> (default: <tt class="docutils literal"><span class="pre">&quot;%prog</span> <span class="pre">[options]&quot;</span></tt>)</dt>
<dd>The usage summary to print when your program is run incorrectly or with a help
option.  When <tt class="xref docutils literal"><span class="pre">optparse</span></tt> prints the usage string, it expands <tt class="docutils literal"><span class="pre">%prog</span></tt> to
<tt class="docutils literal"><span class="pre">os.path.basename(sys.argv[0])</span></tt> (or to <tt class="docutils literal"><span class="pre">prog</span></tt> if you passed that keyword
argument).  To suppress a usage message, pass the special value
<tt class="docutils literal"><span class="pre">optparse.SUPPRESS_USAGE</span></tt>.</dd>
<dt><tt class="docutils literal"><span class="pre">option_list</span></tt> (default: <tt class="docutils literal"><span class="pre">[]</span></tt>)</dt>
<dd>A list of Option objects to populate the parser with.  The options in
<tt class="docutils literal"><span class="pre">option_list</span></tt> are added after any options in <tt class="docutils literal"><span class="pre">standard_option_list</span></tt> (a class
attribute that may be set by OptionParser subclasses), but before any version or
help options. Deprecated; use <tt class="xref docutils literal"><span class="pre">add_option()</span></tt> after creating the parser
instead.</dd>
<dt><tt class="docutils literal"><span class="pre">option_class</span></tt> (default: optparse.Option)</dt>
<dd>Class to use when adding options to the parser in <tt class="xref docutils literal"><span class="pre">add_option()</span></tt>.</dd>
<dt><tt class="docutils literal"><span class="pre">version</span></tt> (default: <tt class="xref docutils literal"><span class="pre">None</span></tt>)</dt>
<dd>A version string to print when the user supplies a version option. If you supply
a true value for <tt class="docutils literal"><span class="pre">version</span></tt>, <tt class="xref docutils literal"><span class="pre">optparse</span></tt> automatically adds a version
option with the single option string <tt class="docutils literal"><span class="pre">&quot;--version&quot;</span></tt>.  The substring <tt class="docutils literal"><span class="pre">&quot;%prog&quot;</span></tt>
is expanded the same as for <tt class="docutils literal"><span class="pre">usage</span></tt>.</dd>
<dt><tt class="docutils literal"><span class="pre">conflict_handler</span></tt> (default: <tt class="docutils literal"><span class="pre">&quot;error&quot;</span></tt>)</dt>
<dd>Specifies what to do when options with conflicting option strings are added to
the parser; see section <a class="reference internal" href="#optparse-conflicts-between-options"><em>Conflicts between options</em></a>.</dd>
<dt><tt class="docutils literal"><span class="pre">description</span></tt> (default: <tt class="xref docutils literal"><span class="pre">None</span></tt>)</dt>
<dd>A paragraph of text giving a brief overview of your program.  <tt class="xref docutils literal"><span class="pre">optparse</span></tt>
reformats this paragraph to fit the current terminal width and prints it when
the user requests help (after <tt class="docutils literal"><span class="pre">usage</span></tt>, but before the list of options).</dd>
<dt><tt class="docutils literal"><span class="pre">formatter</span></tt> (default: a new IndentedHelpFormatter)</dt>
<dd>An instance of optparse.HelpFormatter that will be used for printing help text.
<tt class="xref docutils literal"><span class="pre">optparse</span></tt> provides two concrete classes for this purpose:
IndentedHelpFormatter and TitledHelpFormatter.</dd>
<dt><tt class="docutils literal"><span class="pre">add_help_option</span></tt> (default: <tt class="xref docutils literal"><span class="pre">True</span></tt>)</dt>
<dd>If true, <tt class="xref docutils literal"><span class="pre">optparse</span></tt> will add a help option (with option strings <tt class="docutils literal"><span class="pre">&quot;-h&quot;</span></tt>
and <tt class="docutils literal"><span class="pre">&quot;--help&quot;</span></tt>) to the parser.</dd>
<dt><tt class="docutils literal"><span class="pre">prog</span></tt></dt>
<dd>The string to use when expanding <tt class="docutils literal"><span class="pre">&quot;%prog&quot;</span></tt> in <tt class="docutils literal"><span class="pre">usage</span></tt> and <tt class="docutils literal"><span class="pre">version</span></tt>
instead of <tt class="docutils literal"><span class="pre">os.path.basename(sys.argv[0])</span></tt>.</dd>
</dl>
</blockquote>
</div>
<div class="section" id="populating-the-parser">
<span id="optparse-populating-parser"></span><h3>16.4.3.2. Populating the parser<a class="headerlink" href="#populating-the-parser" title="Permalink to this headline">¶</a></h3>
<p>There are several ways to populate the parser with options.  The preferred way
is by using <tt class="docutils literal"><span class="pre">OptionParser.add_option()</span></tt>, as shown in section
<a class="reference internal" href="#optparse-tutorial"><em>Tutorial</em></a>.  <tt class="xref docutils literal"><span class="pre">add_option()</span></tt> can be called in one of two ways:</p>
<ul class="simple">
<li>pass it an Option instance (as returned by <tt class="xref docutils literal"><span class="pre">make_option()</span></tt>)</li>
<li>pass it any combination of positional and keyword arguments that are
acceptable to <tt class="xref docutils literal"><span class="pre">make_option()</span></tt> (i.e., to the Option constructor), and it will
create the Option instance for you</li>
</ul>
<p>The other alternative is to pass a list of pre-constructed Option instances to
the OptionParser constructor, as in:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">option_list</span> <span class="o">=</span> <span class="p">[</span>
    <span class="n">make_option</span><span class="p">(</span><span class="s">&quot;-f&quot;</span><span class="p">,</span> <span class="s">&quot;--filename&quot;</span><span class="p">,</span>
                <span class="n">action</span><span class="o">=</span><span class="s">&quot;store&quot;</span><span class="p">,</span> <span class="nb">type</span><span class="o">=</span><span class="s">&quot;string&quot;</span><span class="p">,</span> <span class="n">dest</span><span class="o">=</span><span class="s">&quot;filename&quot;</span><span class="p">),</span>
    <span class="n">make_option</span><span class="p">(</span><span class="s">&quot;-q&quot;</span><span class="p">,</span> <span class="s">&quot;--quiet&quot;</span><span class="p">,</span>
                <span class="n">action</span><span class="o">=</span><span class="s">&quot;store_false&quot;</span><span class="p">,</span> <span class="n">dest</span><span class="o">=</span><span class="s">&quot;verbose&quot;</span><span class="p">),</span>
    <span class="p">]</span>
<span class="n">parser</span> <span class="o">=</span> <span class="n">OptionParser</span><span class="p">(</span><span class="n">option_list</span><span class="o">=</span><span class="n">option_list</span><span class="p">)</span>
</pre></div>
</div>
<p>(<tt class="xref docutils literal"><span class="pre">make_option()</span></tt> is a factory function for creating Option instances;
currently it is an alias for the Option constructor.  A future version of
<tt class="xref docutils literal"><span class="pre">optparse</span></tt> may split Option into several classes, and <tt class="xref docutils literal"><span class="pre">make_option()</span></tt>
will pick the right class to instantiate.  Do not instantiate Option directly.)</p>
</div>
<div class="section" id="defining-options">
<span id="optparse-defining-options"></span><h3>16.4.3.3. Defining options<a class="headerlink" href="#defining-options" title="Permalink to this headline">¶</a></h3>
<p>Each Option instance represents a set of synonymous command-line option strings,
e.g. <em class="xref">-f</em> and <em class="xref">--file</em>.  You can specify any number of short or
long option strings, but you must specify at least one overall option string.</p>
<p>The canonical way to create an Option instance is with the <tt class="xref docutils literal"><span class="pre">add_option()</span></tt>
method of <tt class="xref docutils literal"><span class="pre">OptionParser</span></tt>:</p>
<div class="highlight-python"><pre>parser.add_option(opt_str[, ...], attr=value, ...)</pre>
</div>
<p>To define an option with only a short option string:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s">&quot;-f&quot;</span><span class="p">,</span> <span class="n">attr</span><span class="o">=</span><span class="n">value</span><span class="p">,</span> <span class="o">...</span><span class="p">)</span>
</pre></div>
</div>
<p>And to define an option with only a long option string:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s">&quot;--foo&quot;</span><span class="p">,</span> <span class="n">attr</span><span class="o">=</span><span class="n">value</span><span class="p">,</span> <span class="o">...</span><span class="p">)</span>
</pre></div>
</div>
<p>The keyword arguments define attributes of the new Option object.  The most
important option attribute is <tt class="xref docutils literal"><span class="pre">action</span></tt>, and it largely determines which
other attributes are relevant or required.  If you pass irrelevant option
attributes, or fail to pass required ones, <tt class="xref docutils literal"><span class="pre">optparse</span></tt> raises an
<tt class="xref docutils literal"><span class="pre">OptionError</span></tt> exception explaining your mistake.</p>
<p>An option&#8217;s <em>action</em> determines what <tt class="xref docutils literal"><span class="pre">optparse</span></tt> does when it encounters
this option on the command-line.  The standard option actions hard-coded into
<tt class="xref docutils literal"><span class="pre">optparse</span></tt> are:</p>
<dl class="docutils">
<dt><tt class="docutils literal"><span class="pre">store</span></tt></dt>
<dd>store this option&#8217;s argument (default)</dd>
<dt><tt class="docutils literal"><span class="pre">store_const</span></tt></dt>
<dd>store a constant value</dd>
<dt><tt class="docutils literal"><span class="pre">store_true</span></tt></dt>
<dd>store a true value</dd>
<dt><tt class="docutils literal"><span class="pre">store_false</span></tt></dt>
<dd>store a false value</dd>
<dt><tt class="docutils literal"><span class="pre">append</span></tt></dt>
<dd>append this option&#8217;s argument to a list</dd>
<dt><tt class="docutils literal"><span class="pre">append_const</span></tt></dt>
<dd>append a constant value to a list</dd>
<dt><tt class="docutils literal"><span class="pre">count</span></tt></dt>
<dd>increment a counter by one</dd>
<dt><tt class="docutils literal"><span class="pre">callback</span></tt></dt>
<dd>call a specified function</dd>
<dt><a title="help" class="reference external" href="functions.html#help"><tt class="xref docutils literal"><span class="pre">help</span></tt></a></dt>
<dd>print a usage message including all options and the documentation for them</dd>
</dl>
<p>(If you don&#8217;t supply an action, the default is <tt class="docutils literal"><span class="pre">store</span></tt>.  For this action, you
may also supply <a title="type" class="reference external" href="functions.html#type"><tt class="xref docutils literal"><span class="pre">type</span></tt></a> and <tt class="xref docutils literal"><span class="pre">dest</span></tt> option attributes; see below.)</p>
<p>As you can see, most actions involve storing or updating a value somewhere.
<tt class="xref docutils literal"><span class="pre">optparse</span></tt> always creates a special object for this, conventionally called
<tt class="docutils literal"><span class="pre">options</span></tt> (it happens to be an instance of <tt class="docutils literal"><span class="pre">optparse.Values</span></tt>).  Option
arguments (and various other values) are stored as attributes of this object,
according to the <tt class="xref docutils literal"><span class="pre">dest</span></tt> (destination) option attribute.</p>
<p>For example, when you call</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">()</span>
</pre></div>
</div>
<p>one of the first things <tt class="xref docutils literal"><span class="pre">optparse</span></tt> does is create the <tt class="docutils literal"><span class="pre">options</span></tt> object:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">options</span> <span class="o">=</span> <span class="n">Values</span><span class="p">()</span>
</pre></div>
</div>
<p>If one of the options in this parser is defined with</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s">&quot;-f&quot;</span><span class="p">,</span> <span class="s">&quot;--file&quot;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s">&quot;store&quot;</span><span class="p">,</span> <span class="nb">type</span><span class="o">=</span><span class="s">&quot;string&quot;</span><span class="p">,</span> <span class="n">dest</span><span class="o">=</span><span class="s">&quot;filename&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>and the command-line being parsed includes any of the following:</p>
<div class="highlight-python"><pre>-ffoo
-f foo
--file=foo
--file foo</pre>
</div>
<p>then <tt class="xref docutils literal"><span class="pre">optparse</span></tt>, on seeing this option, will do the equivalent of</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">options</span><span class="o">.</span><span class="n">filename</span> <span class="o">=</span> <span class="s">&quot;foo&quot;</span>
</pre></div>
</div>
<p>The <a title="type" class="reference external" href="functions.html#type"><tt class="xref docutils literal"><span class="pre">type</span></tt></a> and <tt class="xref docutils literal"><span class="pre">dest</span></tt> option attributes are almost as important as
<tt class="xref docutils literal"><span class="pre">action</span></tt>, but <tt class="xref docutils literal"><span class="pre">action</span></tt> is the only one that makes sense for <em>all</em>
options.</p>
</div>
<div class="section" id="standard-option-actions">
<span id="optparse-standard-option-actions"></span><h3>16.4.3.4. Standard option actions<a class="headerlink" href="#standard-option-actions" title="Permalink to this headline">¶</a></h3>
<p>The various option actions all have slightly different requirements and effects.
Most actions have several relevant option attributes which you may specify to
guide <tt class="xref docutils literal"><span class="pre">optparse</span></tt>&#8216;s behaviour; a few have required attributes, which you
must specify for any option using that action.</p>
<ul>
<li><p class="first"><tt class="docutils literal"><span class="pre">store</span></tt> [relevant: <a title="type" class="reference external" href="functions.html#type"><tt class="xref docutils literal"><span class="pre">type</span></tt></a>, <tt class="xref docutils literal"><span class="pre">dest</span></tt>, <tt class="docutils literal"><span class="pre">nargs</span></tt>, <tt class="docutils literal"><span class="pre">choices</span></tt>]</p>
<p>The option must be followed by an argument, which is converted to a value
according to <a title="type" class="reference external" href="functions.html#type"><tt class="xref docutils literal"><span class="pre">type</span></tt></a> and stored in <tt class="xref docutils literal"><span class="pre">dest</span></tt>.  If <tt class="docutils literal"><span class="pre">nargs</span></tt> &gt; 1,
multiple arguments will be consumed from the command line; all will be converted
according to <a title="type" class="reference external" href="functions.html#type"><tt class="xref docutils literal"><span class="pre">type</span></tt></a> and stored to <tt class="xref docutils literal"><span class="pre">dest</span></tt> as a tuple.  See the
&#8220;Option types&#8221; section below.</p>
<p>If <tt class="docutils literal"><span class="pre">choices</span></tt> is supplied (a list or tuple of strings), the type defaults to
<tt class="docutils literal"><span class="pre">choice</span></tt>.</p>
<p>If <a title="type" class="reference external" href="functions.html#type"><tt class="xref docutils literal"><span class="pre">type</span></tt></a> is not supplied, it defaults to <tt class="docutils literal"><span class="pre">string</span></tt>.</p>
<p>If <tt class="xref docutils literal"><span class="pre">dest</span></tt> is not supplied, <tt class="xref docutils literal"><span class="pre">optparse</span></tt> derives a destination from the
first long option string (e.g., <tt class="docutils literal"><span class="pre">&quot;--foo-bar&quot;</span></tt> implies <tt class="docutils literal"><span class="pre">foo_bar</span></tt>). If there
are no long option strings, <tt class="xref docutils literal"><span class="pre">optparse</span></tt> derives a destination from the first
short option string (e.g., <tt class="docutils literal"><span class="pre">&quot;-f&quot;</span></tt> implies <tt class="docutils literal"><span class="pre">f</span></tt>).</p>
<p>Example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s">&quot;-f&quot;</span><span class="p">)</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s">&quot;-p&quot;</span><span class="p">,</span> <span class="nb">type</span><span class="o">=</span><span class="s">&quot;float&quot;</span><span class="p">,</span> <span class="n">nargs</span><span class="o">=</span><span class="mf">3</span><span class="p">,</span> <span class="n">dest</span><span class="o">=</span><span class="s">&quot;point&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>As it parses the command line</p>
<div class="highlight-python"><pre>-f foo.txt -p 1 -3.5 4 -fbar.txt</pre>
</div>
<p><tt class="xref docutils literal"><span class="pre">optparse</span></tt> will set</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">options</span><span class="o">.</span><span class="n">f</span> <span class="o">=</span> <span class="s">&quot;foo.txt&quot;</span>
<span class="n">options</span><span class="o">.</span><span class="n">point</span> <span class="o">=</span> <span class="p">(</span><span class="mf">1.0</span><span class="p">,</span> <span class="o">-</span><span class="mf">3.5</span><span class="p">,</span> <span class="mf">4.0</span><span class="p">)</span>
<span class="n">options</span><span class="o">.</span><span class="n">f</span> <span class="o">=</span> <span class="s">&quot;bar.txt&quot;</span>
</pre></div>
</div>
</li>
<li><p class="first"><tt class="docutils literal"><span class="pre">store_const</span></tt> [required: <tt class="docutils literal"><span class="pre">const</span></tt>; relevant: <tt class="xref docutils literal"><span class="pre">dest</span></tt>]</p>
<p>The value <tt class="docutils literal"><span class="pre">const</span></tt> is stored in <tt class="xref docutils literal"><span class="pre">dest</span></tt>.</p>
<p>Example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s">&quot;-q&quot;</span><span class="p">,</span> <span class="s">&quot;--quiet&quot;</span><span class="p">,</span>
                  <span class="n">action</span><span class="o">=</span><span class="s">&quot;store_const&quot;</span><span class="p">,</span> <span class="n">const</span><span class="o">=</span><span class="mf">0</span><span class="p">,</span> <span class="n">dest</span><span class="o">=</span><span class="s">&quot;verbose&quot;</span><span class="p">)</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s">&quot;-v&quot;</span><span class="p">,</span> <span class="s">&quot;--verbose&quot;</span><span class="p">,</span>
                  <span class="n">action</span><span class="o">=</span><span class="s">&quot;store_const&quot;</span><span class="p">,</span> <span class="n">const</span><span class="o">=</span><span class="mf">1</span><span class="p">,</span> <span class="n">dest</span><span class="o">=</span><span class="s">&quot;verbose&quot;</span><span class="p">)</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s">&quot;--noisy&quot;</span><span class="p">,</span>
                  <span class="n">action</span><span class="o">=</span><span class="s">&quot;store_const&quot;</span><span class="p">,</span> <span class="n">const</span><span class="o">=</span><span class="mf">2</span><span class="p">,</span> <span class="n">dest</span><span class="o">=</span><span class="s">&quot;verbose&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>If <tt class="docutils literal"><span class="pre">&quot;--noisy&quot;</span></tt> is seen, <tt class="xref docutils literal"><span class="pre">optparse</span></tt> will set</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">options</span><span class="o">.</span><span class="n">verbose</span> <span class="o">=</span> <span class="mf">2</span>
</pre></div>
</div>
</li>
<li><p class="first"><tt class="docutils literal"><span class="pre">store_true</span></tt> [relevant: <tt class="xref docutils literal"><span class="pre">dest</span></tt>]</p>
<p>A special case of <tt class="docutils literal"><span class="pre">store_const</span></tt> that stores a true value to <tt class="xref docutils literal"><span class="pre">dest</span></tt>.</p>
</li>
<li><p class="first"><tt class="docutils literal"><span class="pre">store_false</span></tt> [relevant: <tt class="xref docutils literal"><span class="pre">dest</span></tt>]</p>
<p>Like <tt class="docutils literal"><span class="pre">store_true</span></tt>, but stores a false value.</p>
<p>Example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s">&quot;--clobber&quot;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s">&quot;store_true&quot;</span><span class="p">,</span> <span class="n">dest</span><span class="o">=</span><span class="s">&quot;clobber&quot;</span><span class="p">)</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s">&quot;--no-clobber&quot;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s">&quot;store_false&quot;</span><span class="p">,</span> <span class="n">dest</span><span class="o">=</span><span class="s">&quot;clobber&quot;</span><span class="p">)</span>
</pre></div>
</div>
</li>
<li><p class="first"><tt class="docutils literal"><span class="pre">append</span></tt> [relevant: <a title="type" class="reference external" href="functions.html#type"><tt class="xref docutils literal"><span class="pre">type</span></tt></a>, <tt class="xref docutils literal"><span class="pre">dest</span></tt>, <tt class="docutils literal"><span class="pre">nargs</span></tt>, <tt class="docutils literal"><span class="pre">choices</span></tt>]</p>
<p>The option must be followed by an argument, which is appended to the list in
<tt class="xref docutils literal"><span class="pre">dest</span></tt>.  If no default value for <tt class="xref docutils literal"><span class="pre">dest</span></tt> is supplied, an empty list
is automatically created when <tt class="xref docutils literal"><span class="pre">optparse</span></tt> first encounters this option on
the command-line.  If <tt class="docutils literal"><span class="pre">nargs</span></tt> &gt; 1, multiple arguments are consumed, and a
tuple of length <tt class="docutils literal"><span class="pre">nargs</span></tt> is appended to <tt class="xref docutils literal"><span class="pre">dest</span></tt>.</p>
<p>The defaults for <a title="type" class="reference external" href="functions.html#type"><tt class="xref docutils literal"><span class="pre">type</span></tt></a> and <tt class="xref docutils literal"><span class="pre">dest</span></tt> are the same as for the <tt class="docutils literal"><span class="pre">store</span></tt>
action.</p>
<p>Example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s">&quot;-t&quot;</span><span class="p">,</span> <span class="s">&quot;--tracks&quot;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s">&quot;append&quot;</span><span class="p">,</span> <span class="nb">type</span><span class="o">=</span><span class="s">&quot;int&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>If <tt class="docutils literal"><span class="pre">&quot;-t3&quot;</span></tt> is seen on the command-line, <tt class="xref docutils literal"><span class="pre">optparse</span></tt> does the equivalent
of:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">options</span><span class="o">.</span><span class="n">tracks</span> <span class="o">=</span> <span class="p">[]</span>
<span class="n">options</span><span class="o">.</span><span class="n">tracks</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="nb">int</span><span class="p">(</span><span class="s">&quot;3&quot;</span><span class="p">))</span>
</pre></div>
</div>
<p>If, a little later on, <tt class="docutils literal"><span class="pre">&quot;--tracks=4&quot;</span></tt> is seen, it does:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">options</span><span class="o">.</span><span class="n">tracks</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="nb">int</span><span class="p">(</span><span class="s">&quot;4&quot;</span><span class="p">))</span>
</pre></div>
</div>
</li>
<li><p class="first"><tt class="docutils literal"><span class="pre">append_const</span></tt> [required: <tt class="docutils literal"><span class="pre">const</span></tt>; relevant: <tt class="xref docutils literal"><span class="pre">dest</span></tt>]</p>
<p>Like <tt class="docutils literal"><span class="pre">store_const</span></tt>, but the value <tt class="docutils literal"><span class="pre">const</span></tt> is appended to <tt class="xref docutils literal"><span class="pre">dest</span></tt>; as
with <tt class="docutils literal"><span class="pre">append</span></tt>, <tt class="xref docutils literal"><span class="pre">dest</span></tt> defaults to <tt class="xref docutils literal"><span class="pre">None</span></tt>, and an empty list is
automatically created the first time the option is encountered.</p>
</li>
<li><p class="first"><tt class="docutils literal"><span class="pre">count</span></tt> [relevant: <tt class="xref docutils literal"><span class="pre">dest</span></tt>]</p>
<p>Increment the integer stored at <tt class="xref docutils literal"><span class="pre">dest</span></tt>.  If no default value is supplied,
<tt class="xref docutils literal"><span class="pre">dest</span></tt> is set to zero before being incremented the first time.</p>
<p>Example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s">&quot;-v&quot;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s">&quot;count&quot;</span><span class="p">,</span> <span class="n">dest</span><span class="o">=</span><span class="s">&quot;verbosity&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>The first time <tt class="docutils literal"><span class="pre">&quot;-v&quot;</span></tt> is seen on the command line, <tt class="xref docutils literal"><span class="pre">optparse</span></tt> does the
equivalent of:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">options</span><span class="o">.</span><span class="n">verbosity</span> <span class="o">=</span> <span class="mf">0</span>
<span class="n">options</span><span class="o">.</span><span class="n">verbosity</span> <span class="o">+=</span> <span class="mf">1</span>
</pre></div>
</div>
<p>Every subsequent occurrence of <tt class="docutils literal"><span class="pre">&quot;-v&quot;</span></tt> results in</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">options</span><span class="o">.</span><span class="n">verbosity</span> <span class="o">+=</span> <span class="mf">1</span>
</pre></div>
</div>
</li>
<li><p class="first"><tt class="docutils literal"><span class="pre">callback</span></tt> [required: <tt class="docutils literal"><span class="pre">callback</span></tt>; relevant: <a title="type" class="reference external" href="functions.html#type"><tt class="xref docutils literal"><span class="pre">type</span></tt></a>, <tt class="docutils literal"><span class="pre">nargs</span></tt>,
<tt class="docutils literal"><span class="pre">callback_args</span></tt>, <tt class="docutils literal"><span class="pre">callback_kwargs</span></tt>]</p>
<p>Call the function specified by <tt class="docutils literal"><span class="pre">callback</span></tt>, which is called as</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">func</span><span class="p">(</span><span class="n">option</span><span class="p">,</span> <span class="n">opt_str</span><span class="p">,</span> <span class="n">value</span><span class="p">,</span> <span class="n">parser</span><span class="p">,</span> <span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">)</span>
</pre></div>
</div>
<p>See section <a class="reference internal" href="#optparse-option-callbacks"><em>Option Callbacks</em></a> for more detail.</p>
</li>
<li><p class="first"><a title="help" class="reference external" href="functions.html#help"><tt class="xref docutils literal"><span class="pre">help</span></tt></a></p>
<p>Prints a complete help message for all the options in the current option parser.
The help message is constructed from the <tt class="docutils literal"><span class="pre">usage</span></tt> string passed to
OptionParser&#8217;s constructor and the <a title="help" class="reference external" href="functions.html#help"><tt class="xref docutils literal"><span class="pre">help</span></tt></a> string passed to every option.</p>
<p>If no <a title="help" class="reference external" href="functions.html#help"><tt class="xref docutils literal"><span class="pre">help</span></tt></a> string is supplied for an option, it will still be listed in
the help message.  To omit an option entirely, use the special value
<tt class="docutils literal"><span class="pre">optparse.SUPPRESS_HELP</span></tt>.</p>
<p><tt class="xref docutils literal"><span class="pre">optparse</span></tt> automatically adds a <a title="help" class="reference external" href="functions.html#help"><tt class="xref docutils literal"><span class="pre">help</span></tt></a> option to all OptionParsers,
so you do not normally need to create one.</p>
<p>Example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">optparse</span> <span class="kn">import</span> <span class="n">OptionParser</span><span class="p">,</span> <span class="n">SUPPRESS_HELP</span>

<span class="n">parser</span> <span class="o">=</span> <span class="n">OptionParser</span><span class="p">()</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s">&quot;-h&quot;</span><span class="p">,</span> <span class="s">&quot;--help&quot;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s">&quot;help&quot;</span><span class="p">),</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s">&quot;-v&quot;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s">&quot;store_true&quot;</span><span class="p">,</span> <span class="n">dest</span><span class="o">=</span><span class="s">&quot;verbose&quot;</span><span class="p">,</span>
                  <span class="n">help</span><span class="o">=</span><span class="s">&quot;Be moderately verbose&quot;</span><span class="p">)</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s">&quot;--file&quot;</span><span class="p">,</span> <span class="n">dest</span><span class="o">=</span><span class="s">&quot;filename&quot;</span><span class="p">,</span>
                  <span class="n">help</span><span class="o">=</span><span class="s">&quot;Input file to read data from&quot;</span><span class="p">),</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s">&quot;--secret&quot;</span><span class="p">,</span> <span class="n">help</span><span class="o">=</span><span class="n">SUPPRESS_HELP</span><span class="p">)</span>
</pre></div>
</div>
<p>If <tt class="xref docutils literal"><span class="pre">optparse</span></tt> sees either <tt class="docutils literal"><span class="pre">&quot;-h&quot;</span></tt> or <tt class="docutils literal"><span class="pre">&quot;--help&quot;</span></tt> on the command line, it
will print something like the following help message to stdout (assuming
<tt class="docutils literal"><span class="pre">sys.argv[0]</span></tt> is <tt class="docutils literal"><span class="pre">&quot;foo.py&quot;</span></tt>):</p>
<div class="highlight-python"><pre>usage: foo.py [options]

options:
  -h, --help        Show this help message and exit
  -v                Be moderately verbose
  --file=FILENAME   Input file to read data from</pre>
</div>
<p>After printing the help message, <tt class="xref docutils literal"><span class="pre">optparse</span></tt> terminates your process with
<tt class="docutils literal"><span class="pre">sys.exit(0)</span></tt>.</p>
</li>
<li><p class="first"><tt class="docutils literal"><span class="pre">version</span></tt></p>
<p>Prints the version number supplied to the OptionParser to stdout and exits.  The
version number is actually formatted and printed by the <tt class="docutils literal"><span class="pre">print_version()</span></tt>
method of OptionParser.  Generally only relevant if the <tt class="docutils literal"><span class="pre">version</span></tt> argument is
supplied to the OptionParser constructor.  As with <a title="help" class="reference external" href="functions.html#help"><tt class="xref docutils literal"><span class="pre">help</span></tt></a> options, you
will rarely create <tt class="docutils literal"><span class="pre">version</span></tt> options, since <tt class="xref docutils literal"><span class="pre">optparse</span></tt> automatically adds
them when needed.</p>
</li>
</ul>
</div>
<div class="section" id="option-attributes">
<span id="optparse-option-attributes"></span><h3>16.4.3.5. Option attributes<a class="headerlink" href="#option-attributes" title="Permalink to this headline">¶</a></h3>
<p>The following option attributes may be passed as keyword arguments to
<tt class="docutils literal"><span class="pre">parser.add_option()</span></tt>.  If you pass an option attribute that is not relevant
to a particular option, or fail to pass a required option attribute,
<tt class="xref docutils literal"><span class="pre">optparse</span></tt> raises <tt class="xref docutils literal"><span class="pre">OptionError</span></tt>.</p>
<ul>
<li><p class="first"><tt class="xref docutils literal"><span class="pre">action</span></tt> (default: <tt class="docutils literal"><span class="pre">&quot;store&quot;</span></tt>)</p>
<p>Determines <tt class="xref docutils literal"><span class="pre">optparse</span></tt>&#8216;s behaviour when this option is seen on the command
line; the available options are documented above.</p>
</li>
<li><p class="first"><a title="type" class="reference external" href="functions.html#type"><tt class="xref docutils literal"><span class="pre">type</span></tt></a> (default: <tt class="docutils literal"><span class="pre">&quot;string&quot;</span></tt>)</p>
<p>The argument type expected by this option (e.g., <tt class="docutils literal"><span class="pre">&quot;string&quot;</span></tt> or <tt class="docutils literal"><span class="pre">&quot;int&quot;</span></tt>); the
available option types are documented below.</p>
</li>
<li><p class="first"><tt class="xref docutils literal"><span class="pre">dest</span></tt> (default: derived from option strings)</p>
<p>If the option&#8217;s action implies writing or modifying a value somewhere, this
tells <tt class="xref docutils literal"><span class="pre">optparse</span></tt> where to write it: <tt class="xref docutils literal"><span class="pre">dest</span></tt> names an attribute of the
<tt class="docutils literal"><span class="pre">options</span></tt> object that <tt class="xref docutils literal"><span class="pre">optparse</span></tt> builds as it parses the command line.</p>
</li>
<li><p class="first"><tt class="docutils literal"><span class="pre">default</span></tt> (deprecated)</p>
<p>The value to use for this option&#8217;s destination if the option is not seen on the
command line.  Deprecated; use <tt class="docutils literal"><span class="pre">parser.set_defaults()</span></tt> instead.</p>
</li>
<li><p class="first"><tt class="docutils literal"><span class="pre">nargs</span></tt> (default: 1)</p>
<p>How many arguments of type <a title="type" class="reference external" href="functions.html#type"><tt class="xref docutils literal"><span class="pre">type</span></tt></a> should be consumed when this option is
seen.  If &gt; 1, <tt class="xref docutils literal"><span class="pre">optparse</span></tt> will store a tuple of values to <tt class="xref docutils literal"><span class="pre">dest</span></tt>.</p>
</li>
<li><p class="first"><tt class="docutils literal"><span class="pre">const</span></tt></p>
<p>For actions that store a constant value, the constant value to store.</p>
</li>
<li><p class="first"><tt class="docutils literal"><span class="pre">choices</span></tt></p>
<p>For options of type <tt class="docutils literal"><span class="pre">&quot;choice&quot;</span></tt>, the list of strings the user may choose from.</p>
</li>
<li><p class="first"><tt class="docutils literal"><span class="pre">callback</span></tt></p>
<p>For options with action <tt class="docutils literal"><span class="pre">&quot;callback&quot;</span></tt>, the callable to call when this option
is seen.  See section <a class="reference internal" href="#optparse-option-callbacks"><em>Option Callbacks</em></a> for detail on the
arguments passed to <tt class="docutils literal"><span class="pre">callable</span></tt>.</p>
</li>
<li><p class="first"><tt class="docutils literal"><span class="pre">callback_args</span></tt>, <tt class="docutils literal"><span class="pre">callback_kwargs</span></tt></p>
<p>Additional positional and keyword arguments to pass to <tt class="docutils literal"><span class="pre">callback</span></tt> after the
four standard callback arguments.</p>
</li>
<li><p class="first"><a title="help" class="reference external" href="functions.html#help"><tt class="xref docutils literal"><span class="pre">help</span></tt></a></p>
<p>Help text to print for this option when listing all available options after the
user supplies a <a title="help" class="reference external" href="functions.html#help"><tt class="xref docutils literal"><span class="pre">help</span></tt></a> option (such as <tt class="docutils literal"><span class="pre">&quot;--help&quot;</span></tt>). If no help text is
supplied, the option will be listed without help text.  To hide this option, use
the special value <tt class="docutils literal"><span class="pre">SUPPRESS_HELP</span></tt>.</p>
</li>
<li><p class="first"><tt class="docutils literal"><span class="pre">metavar</span></tt> (default: derived from option strings)</p>
<p>Stand-in for the option argument(s) to use when printing help text. See section
<a class="reference internal" href="#optparse-tutorial"><em>Tutorial</em></a> for an example.</p>
</li>
</ul>
</div>
<div class="section" id="standard-option-types">
<span id="optparse-standard-option-types"></span><h3>16.4.3.6. Standard option types<a class="headerlink" href="#standard-option-types" title="Permalink to this headline">¶</a></h3>
<p><tt class="xref docutils literal"><span class="pre">optparse</span></tt> has six built-in option types: <tt class="docutils literal"><span class="pre">string</span></tt>, <tt class="docutils literal"><span class="pre">int</span></tt>, <tt class="docutils literal"><span class="pre">long</span></tt>,
<tt class="docutils literal"><span class="pre">choice</span></tt>, <tt class="docutils literal"><span class="pre">float</span></tt> and <tt class="docutils literal"><span class="pre">complex</span></tt>.  If you need to add new option types, see
section <a class="reference internal" href="#optparse-extending-optparse"><em>Extending optparse</em></a>.</p>
<p>Arguments to string options are not checked or converted in any way: the text on
the command line is stored in the destination (or passed to the callback) as-is.</p>
<p>Integer arguments (type <tt class="docutils literal"><span class="pre">int</span></tt> or <tt class="docutils literal"><span class="pre">long</span></tt>) are parsed as follows:</p>
<ul class="simple">
<li>if the number starts with <tt class="docutils literal"><span class="pre">0x</span></tt>, it is parsed as a hexadecimal number</li>
<li>if the number starts with <tt class="docutils literal"><span class="pre">0</span></tt>, it is parsed as an octal number</li>
<li>if the number starts with <tt class="docutils literal"><span class="pre">0b</span></tt>, it is parsed as a binary number</li>
<li>otherwise, the number is parsed as a decimal number</li>
</ul>
<p>The conversion is done by calling either <tt class="docutils literal"><span class="pre">int()</span></tt> or <tt class="docutils literal"><span class="pre">long()</span></tt> with the
appropriate base (2, 8, 10, or 16).  If this fails, so will <tt class="xref docutils literal"><span class="pre">optparse</span></tt>,
although with a more useful error message.</p>
<p><tt class="docutils literal"><span class="pre">float</span></tt> and <tt class="docutils literal"><span class="pre">complex</span></tt> option arguments are converted directly with
<tt class="docutils literal"><span class="pre">float()</span></tt> and <tt class="docutils literal"><span class="pre">complex()</span></tt>, with similar error-handling.</p>
<p><tt class="docutils literal"><span class="pre">choice</span></tt> options are a subtype of <tt class="docutils literal"><span class="pre">string</span></tt> options.  The <tt class="docutils literal"><span class="pre">choices</span></tt> option
attribute (a sequence of strings) defines the set of allowed option arguments.
<tt class="docutils literal"><span class="pre">optparse.check_choice()</span></tt> compares user-supplied option arguments against this
master list and raises <tt class="xref docutils literal"><span class="pre">OptionValueError</span></tt> if an invalid string is given.</p>
</div>
<div class="section" id="parsing-arguments">
<span id="optparse-parsing-arguments"></span><h3>16.4.3.7. Parsing arguments<a class="headerlink" href="#parsing-arguments" title="Permalink to this headline">¶</a></h3>
<p>The whole point of creating and populating an OptionParser is to call its
<tt class="xref docutils literal"><span class="pre">parse_args()</span></tt> method:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="p">(</span><span class="n">options</span><span class="p">,</span> <span class="n">args</span><span class="p">)</span> <span class="o">=</span> <span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">(</span><span class="n">args</span><span class="o">=</span><span class="bp">None</span><span class="p">,</span> <span class="n">values</span><span class="o">=</span><span class="bp">None</span><span class="p">)</span>
</pre></div>
</div>
<p>where the input parameters are</p>
<dl class="docutils">
<dt><tt class="docutils literal"><span class="pre">args</span></tt></dt>
<dd>the list of arguments to process (default: <tt class="docutils literal"><span class="pre">sys.argv[1:]</span></tt>)</dd>
<dt><tt class="docutils literal"><span class="pre">values</span></tt></dt>
<dd>object to store option arguments in (default: a new instance of optparse.Values)</dd>
</dl>
<p>and the return values are</p>
<dl class="docutils">
<dt><tt class="docutils literal"><span class="pre">options</span></tt></dt>
<dd>the same object that was passed in as <tt class="docutils literal"><span class="pre">options</span></tt>, or the optparse.Values
instance created by <tt class="xref docutils literal"><span class="pre">optparse</span></tt></dd>
<dt><tt class="docutils literal"><span class="pre">args</span></tt></dt>
<dd>the leftover positional arguments after all options have been processed</dd>
</dl>
<p>The most common usage is to supply neither keyword argument.  If you supply
<tt class="docutils literal"><span class="pre">options</span></tt>, it will be modified with repeated <tt class="docutils literal"><span class="pre">setattr()</span></tt> calls (roughly one
for every option argument stored to an option destination) and returned by
<tt class="xref docutils literal"><span class="pre">parse_args()</span></tt>.</p>
<p>If <tt class="xref docutils literal"><span class="pre">parse_args()</span></tt> encounters any errors in the argument list, it calls the
OptionParser&#8217;s <tt class="xref docutils literal"><span class="pre">error()</span></tt> method with an appropriate end-user error message.
This ultimately terminates your process with an exit status of 2 (the
traditional Unix exit status for command-line errors).</p>
</div>
<div class="section" id="querying-and-manipulating-your-option-parser">
<span id="optparse-querying-manipulating-option-parser"></span><h3>16.4.3.8. Querying and manipulating your option parser<a class="headerlink" href="#querying-and-manipulating-your-option-parser" title="Permalink to this headline">¶</a></h3>
<p>The default behavior of the option parser can be customized slightly,
and you can also poke around your option parser and see what&#8217;s there.
OptionParser provides several methods to help you out:</p>
<dl class="docutils">
<dt><tt class="docutils literal"><span class="pre">disable_interspersed_args()</span></tt></dt>
<dd>Set parsing to stop on the first non-option. Use this if you have a
command processor which runs another command which has options of
its own and you want to make sure these options don&#8217;t get
confused. For example, each command might have a different
set of options.</dd>
<dt><tt class="docutils literal"><span class="pre">enable_interspersed_args()</span></tt></dt>
<dd>Set parsing to not stop on the first non-option, allowing
interspersing switches with command arguments.  For example,
<tt class="docutils literal"><span class="pre">&quot;-s</span> <span class="pre">arg1</span> <span class="pre">--long</span> <span class="pre">arg2&quot;</span></tt> would return <tt class="docutils literal"><span class="pre">[&quot;arg1&quot;,</span> <span class="pre">&quot;arg2&quot;]</span></tt>
as the command arguments and <tt class="docutils literal"><span class="pre">-s,</span> <span class="pre">--long</span></tt> as options.
This is the default behavior.</dd>
<dt><tt class="docutils literal"><span class="pre">get_option(opt_str)</span></tt></dt>
<dd>Returns the Option instance with the option string <tt class="docutils literal"><span class="pre">opt_str</span></tt>, or <tt class="xref docutils literal"><span class="pre">None</span></tt> if
no options have that option string.</dd>
<dt><tt class="docutils literal"><span class="pre">has_option(opt_str)</span></tt></dt>
<dd>Return true if the OptionParser has an option with option string <tt class="docutils literal"><span class="pre">opt_str</span></tt>
(e.g., <tt class="docutils literal"><span class="pre">&quot;-q&quot;</span></tt> or <tt class="docutils literal"><span class="pre">&quot;--verbose&quot;</span></tt>).</dd>
<dt><tt class="docutils literal"><span class="pre">remove_option(opt_str)</span></tt></dt>
<dd>If the <tt class="xref docutils literal"><span class="pre">OptionParser</span></tt> has an option corresponding to <tt class="docutils literal"><span class="pre">opt_str</span></tt>, that option is
removed.  If that option provided any other option strings, all of those option
strings become invalid. If <tt class="docutils literal"><span class="pre">opt_str</span></tt> does not occur in any option belonging to
this <tt class="xref docutils literal"><span class="pre">OptionParser</span></tt>, raises <a title="exceptions.ValueError" class="reference external" href="exceptions.html#exceptions.ValueError"><tt class="xref docutils literal"><span class="pre">ValueError</span></tt></a>.</dd>
</dl>
</div>
<div class="section" id="conflicts-between-options">
<span id="optparse-conflicts-between-options"></span><h3>16.4.3.9. Conflicts between options<a class="headerlink" href="#conflicts-between-options" title="Permalink to this headline">¶</a></h3>
<p>If you&#8217;re not careful, it&#8217;s easy to define options with conflicting option
strings:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s">&quot;-n&quot;</span><span class="p">,</span> <span class="s">&quot;--dry-run&quot;</span><span class="p">,</span> <span class="o">...</span><span class="p">)</span>
<span class="p">[</span><span class="o">...</span><span class="p">]</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s">&quot;-n&quot;</span><span class="p">,</span> <span class="s">&quot;--noisy&quot;</span><span class="p">,</span> <span class="o">...</span><span class="p">)</span>
</pre></div>
</div>
<p>(This is particularly true if you&#8217;ve defined your own OptionParser subclass with
some standard options.)</p>
<p>Every time you add an option, <tt class="xref docutils literal"><span class="pre">optparse</span></tt> checks for conflicts with existing
options.  If it finds any, it invokes the current conflict-handling mechanism.
You can set the conflict-handling mechanism either in the constructor:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">parser</span> <span class="o">=</span> <span class="n">OptionParser</span><span class="p">(</span><span class="o">...</span><span class="p">,</span> <span class="n">conflict_handler</span><span class="o">=</span><span class="n">handler</span><span class="p">)</span>
</pre></div>
</div>
<p>or with a separate call:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">parser</span><span class="o">.</span><span class="n">set_conflict_handler</span><span class="p">(</span><span class="n">handler</span><span class="p">)</span>
</pre></div>
</div>
<p>The available conflict handlers are:</p>
<blockquote>
<dl class="docutils">
<dt><tt class="docutils literal"><span class="pre">error</span></tt> (default)</dt>
<dd>assume option conflicts are a programming error and raise <tt class="xref docutils literal"><span class="pre">OptionConflictError</span></tt></dd>
<dt><tt class="docutils literal"><span class="pre">resolve</span></tt></dt>
<dd>resolve option conflicts intelligently (see below)</dd>
</dl>
</blockquote>
<p>As an example, let&#8217;s define an <tt class="xref docutils literal"><span class="pre">OptionParser</span></tt> that resolves conflicts
intelligently and add conflicting options to it:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">parser</span> <span class="o">=</span> <span class="n">OptionParser</span><span class="p">(</span><span class="n">conflict_handler</span><span class="o">=</span><span class="s">&quot;resolve&quot;</span><span class="p">)</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s">&quot;-n&quot;</span><span class="p">,</span> <span class="s">&quot;--dry-run&quot;</span><span class="p">,</span> <span class="o">...</span><span class="p">,</span> <span class="n">help</span><span class="o">=</span><span class="s">&quot;do no harm&quot;</span><span class="p">)</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s">&quot;-n&quot;</span><span class="p">,</span> <span class="s">&quot;--noisy&quot;</span><span class="p">,</span> <span class="o">...</span><span class="p">,</span> <span class="n">help</span><span class="o">=</span><span class="s">&quot;be noisy&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>At this point, <tt class="xref docutils literal"><span class="pre">optparse</span></tt> detects that a previously-added option is already
using the <tt class="docutils literal"><span class="pre">&quot;-n&quot;</span></tt> option string.  Since <tt class="docutils literal"><span class="pre">conflict_handler</span></tt> is <tt class="docutils literal"><span class="pre">&quot;resolve&quot;</span></tt>,
it resolves the situation by removing <tt class="docutils literal"><span class="pre">&quot;-n&quot;</span></tt> from the earlier option&#8217;s list of
option strings.  Now <tt class="docutils literal"><span class="pre">&quot;--dry-run&quot;</span></tt> is the only way for the user to activate
that option.  If the user asks for help, the help message will reflect that:</p>
<div class="highlight-python"><pre>options:
  --dry-run     do no harm
  [...]
  -n, --noisy   be noisy</pre>
</div>
<p>It&#8217;s possible to whittle away the option strings for a previously-added option
until there are none left, and the user has no way of invoking that option from
the command-line.  In that case, <tt class="xref docutils literal"><span class="pre">optparse</span></tt> removes that option completely,
so it doesn&#8217;t show up in help text or anywhere else. Carrying on with our
existing OptionParser:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s">&quot;--dry-run&quot;</span><span class="p">,</span> <span class="o">...</span><span class="p">,</span> <span class="n">help</span><span class="o">=</span><span class="s">&quot;new dry-run option&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>At this point, the original <em class="xref">-n/--dry-run</em> option is no longer
accessible, so <tt class="xref docutils literal"><span class="pre">optparse</span></tt> removes it, leaving this help text:</p>
<div class="highlight-python"><pre>options:
  [...]
  -n, --noisy   be noisy
  --dry-run     new dry-run option</pre>
</div>
</div>
<div class="section" id="cleanup">
<span id="optparse-cleanup"></span><h3>16.4.3.10. Cleanup<a class="headerlink" href="#cleanup" title="Permalink to this headline">¶</a></h3>
<p>OptionParser instances have several cyclic references.  This should not be a
problem for Python&#8217;s garbage collector, but you may wish to break the cyclic
references explicitly by calling <tt class="docutils literal"><span class="pre">destroy()</span></tt> on your OptionParser once you are
done with it.  This is particularly useful in long-running applications where
large object graphs are reachable from your OptionParser.</p>
</div>
<div class="section" id="other-methods">
<span id="optparse-other-methods"></span><h3>16.4.3.11. Other methods<a class="headerlink" href="#other-methods" title="Permalink to this headline">¶</a></h3>
<p>OptionParser supports several other public methods:</p>
<ul>
<li><p class="first"><tt class="docutils literal"><span class="pre">set_usage(usage)</span></tt></p>
<p>Set the usage string according to the rules described above for the <tt class="docutils literal"><span class="pre">usage</span></tt>
constructor keyword argument.  Passing <tt class="xref docutils literal"><span class="pre">None</span></tt> sets the default usage string;
use <tt class="docutils literal"><span class="pre">SUPPRESS_USAGE</span></tt> to suppress a usage message.</p>
</li>
<li><p class="first"><tt class="docutils literal"><span class="pre">enable_interspersed_args()</span></tt>, <tt class="docutils literal"><span class="pre">disable_interspersed_args()</span></tt></p>
<p>Enable/disable positional arguments interspersed with options, similar to GNU
getopt (enabled by default).  For example, if <tt class="docutils literal"><span class="pre">&quot;-a&quot;</span></tt> and <tt class="docutils literal"><span class="pre">&quot;-b&quot;</span></tt> are both
simple options that take no arguments, <tt class="xref docutils literal"><span class="pre">optparse</span></tt> normally accepts this
syntax:</p>
<div class="highlight-python"><pre>prog -a arg1 -b arg2</pre>
</div>
<p>and treats it as equivalent to</p>
<div class="highlight-python"><pre>prog -a -b arg1 arg2</pre>
</div>
<p>To disable this feature, call <tt class="docutils literal"><span class="pre">disable_interspersed_args()</span></tt>.  This restores
traditional Unix syntax, where option parsing stops with the first non-option
argument.</p>
</li>
<li><p class="first"><tt class="docutils literal"><span class="pre">set_defaults(dest=value,</span> <span class="pre">...)</span></tt></p>
<p>Set default values for several option destinations at once.  Using
<tt class="xref docutils literal"><span class="pre">set_defaults()</span></tt> is the preferred way to set default values for options,
since multiple options can share the same destination.  For example, if several
&#8220;mode&#8221; options all set the same destination, any one of them can set the
default, and the last one wins:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s">&quot;--advanced&quot;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s">&quot;store_const&quot;</span><span class="p">,</span>
                  <span class="n">dest</span><span class="o">=</span><span class="s">&quot;mode&quot;</span><span class="p">,</span> <span class="n">const</span><span class="o">=</span><span class="s">&quot;advanced&quot;</span><span class="p">,</span>
                  <span class="n">default</span><span class="o">=</span><span class="s">&quot;novice&quot;</span><span class="p">)</span>    <span class="c"># overridden below</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s">&quot;--novice&quot;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s">&quot;store_const&quot;</span><span class="p">,</span>
                  <span class="n">dest</span><span class="o">=</span><span class="s">&quot;mode&quot;</span><span class="p">,</span> <span class="n">const</span><span class="o">=</span><span class="s">&quot;novice&quot;</span><span class="p">,</span>
                  <span class="n">default</span><span class="o">=</span><span class="s">&quot;advanced&quot;</span><span class="p">)</span>  <span class="c"># overrides above setting</span>
</pre></div>
</div>
<p>To avoid this confusion, use <tt class="xref docutils literal"><span class="pre">set_defaults()</span></tt>:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">parser</span><span class="o">.</span><span class="n">set_defaults</span><span class="p">(</span><span class="n">mode</span><span class="o">=</span><span class="s">&quot;advanced&quot;</span><span class="p">)</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s">&quot;--advanced&quot;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s">&quot;store_const&quot;</span><span class="p">,</span>
                  <span class="n">dest</span><span class="o">=</span><span class="s">&quot;mode&quot;</span><span class="p">,</span> <span class="n">const</span><span class="o">=</span><span class="s">&quot;advanced&quot;</span><span class="p">)</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s">&quot;--novice&quot;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s">&quot;store_const&quot;</span><span class="p">,</span>
                  <span class="n">dest</span><span class="o">=</span><span class="s">&quot;mode&quot;</span><span class="p">,</span> <span class="n">const</span><span class="o">=</span><span class="s">&quot;novice&quot;</span><span class="p">)</span>
</pre></div>
</div>
</li>
</ul>
</div>
</div>
<div class="section" id="option-callbacks">
<span id="optparse-option-callbacks"></span><h2>16.4.4. Option Callbacks<a class="headerlink" href="#option-callbacks" title="Permalink to this headline">¶</a></h2>
<p>When <tt class="xref docutils literal"><span class="pre">optparse</span></tt>&#8216;s built-in actions and types aren&#8217;t quite enough for your
needs, you have two choices: extend <tt class="xref docutils literal"><span class="pre">optparse</span></tt> or define a callback option.
Extending <tt class="xref docutils literal"><span class="pre">optparse</span></tt> is more general, but overkill for a lot of simple
cases.  Quite often a simple callback is all you need.</p>
<p>There are two steps to defining a callback option:</p>
<ul class="simple">
<li>define the option itself using the <tt class="docutils literal"><span class="pre">callback</span></tt> action</li>
<li>write the callback; this is a function (or method) that takes at least four
arguments, as described below</li>
</ul>
<div class="section" id="defining-a-callback-option">
<span id="optparse-defining-callback-option"></span><h3>16.4.4.1. Defining a callback option<a class="headerlink" href="#defining-a-callback-option" title="Permalink to this headline">¶</a></h3>
<p>As always, the easiest way to define a callback option is by using the
<tt class="docutils literal"><span class="pre">parser.add_option()</span></tt> method.  Apart from <tt class="xref docutils literal"><span class="pre">action</span></tt>, the only option
attribute you must specify is <tt class="docutils literal"><span class="pre">callback</span></tt>, the function to call:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s">&quot;-c&quot;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s">&quot;callback&quot;</span><span class="p">,</span> <span class="n">callback</span><span class="o">=</span><span class="n">my_callback</span><span class="p">)</span>
</pre></div>
</div>
<p><tt class="docutils literal"><span class="pre">callback</span></tt> is a function (or other callable object), so you must have already
defined <tt class="docutils literal"><span class="pre">my_callback()</span></tt> when you create this callback option. In this simple
case, <tt class="xref docutils literal"><span class="pre">optparse</span></tt> doesn&#8217;t even know if <a class="reference external" href="../using/cmdline.html#cmdoption-c"><em class="xref">-c</em></a> takes any arguments,
which usually means that the option takes no arguments&#8212;the mere presence of
<a class="reference external" href="../using/cmdline.html#cmdoption-c"><em class="xref">-c</em></a> on the command-line is all it needs to know.  In some
circumstances, though, you might want your callback to consume an arbitrary
number of command-line arguments.  This is where writing callbacks gets tricky;
it&#8217;s covered later in this section.</p>
<p><tt class="xref docutils literal"><span class="pre">optparse</span></tt> always passes four particular arguments to your callback, and it
will only pass additional arguments if you specify them via <tt class="docutils literal"><span class="pre">callback_args</span></tt>
and <tt class="docutils literal"><span class="pre">callback_kwargs</span></tt>.  Thus, the minimal callback function signature is:</p>
<div class="highlight-python"><pre>def my_callback(option, opt, value, parser):</pre>
</div>
<p>The four arguments to a callback are described below.</p>
<p>There are several other option attributes that you can supply when you define a
callback option:</p>
<dl class="docutils">
<dt><a title="type" class="reference external" href="functions.html#type"><tt class="xref docutils literal"><span class="pre">type</span></tt></a></dt>
<dd>has its usual meaning: as with the <tt class="docutils literal"><span class="pre">store</span></tt> or <tt class="docutils literal"><span class="pre">append</span></tt> actions, it instructs
<tt class="xref docutils literal"><span class="pre">optparse</span></tt> to consume one argument and convert it to <a title="type" class="reference external" href="functions.html#type"><tt class="xref docutils literal"><span class="pre">type</span></tt></a>.  Rather
than storing the converted value(s) anywhere, though, <tt class="xref docutils literal"><span class="pre">optparse</span></tt> passes it
to your callback function.</dd>
<dt><tt class="docutils literal"><span class="pre">nargs</span></tt></dt>
<dd>also has its usual meaning: if it is supplied and &gt; 1, <tt class="xref docutils literal"><span class="pre">optparse</span></tt> will
consume <tt class="docutils literal"><span class="pre">nargs</span></tt> arguments, each of which must be convertible to <a title="type" class="reference external" href="functions.html#type"><tt class="xref docutils literal"><span class="pre">type</span></tt></a>.
It then passes a tuple of converted values to your callback.</dd>
<dt><tt class="docutils literal"><span class="pre">callback_args</span></tt></dt>
<dd>a tuple of extra positional arguments to pass to the callback</dd>
<dt><tt class="docutils literal"><span class="pre">callback_kwargs</span></tt></dt>
<dd>a dictionary of extra keyword arguments to pass to the callback</dd>
</dl>
</div>
<div class="section" id="how-callbacks-are-called">
<span id="optparse-how-callbacks-called"></span><h3>16.4.4.2. How callbacks are called<a class="headerlink" href="#how-callbacks-are-called" title="Permalink to this headline">¶</a></h3>
<p>All callbacks are called as follows:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">func</span><span class="p">(</span><span class="n">option</span><span class="p">,</span> <span class="n">opt_str</span><span class="p">,</span> <span class="n">value</span><span class="p">,</span> <span class="n">parser</span><span class="p">,</span> <span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">)</span>
</pre></div>
</div>
<p>where</p>
<dl class="docutils">
<dt><tt class="docutils literal"><span class="pre">option</span></tt></dt>
<dd>is the Option instance that&#8217;s calling the callback</dd>
<dt><tt class="docutils literal"><span class="pre">opt_str</span></tt></dt>
<dd>is the option string seen on the command-line that&#8217;s triggering the callback.
(If an abbreviated long option was used, <tt class="docutils literal"><span class="pre">opt_str</span></tt> will be the full, canonical
option string&#8212;e.g. if the user puts <tt class="docutils literal"><span class="pre">&quot;--foo&quot;</span></tt> on the command-line as an
abbreviation for <tt class="docutils literal"><span class="pre">&quot;--foobar&quot;</span></tt>, then <tt class="docutils literal"><span class="pre">opt_str</span></tt> will be <tt class="docutils literal"><span class="pre">&quot;--foobar&quot;</span></tt>.)</dd>
<dt><tt class="docutils literal"><span class="pre">value</span></tt></dt>
<dd>is the argument to this option seen on the command-line.  <tt class="xref docutils literal"><span class="pre">optparse</span></tt> will
only expect an argument if <a title="type" class="reference external" href="functions.html#type"><tt class="xref docutils literal"><span class="pre">type</span></tt></a> is set; the type of <tt class="docutils literal"><span class="pre">value</span></tt> will be
the type implied by the option&#8217;s type.  If <a title="type" class="reference external" href="functions.html#type"><tt class="xref docutils literal"><span class="pre">type</span></tt></a> for this option is
<tt class="xref docutils literal"><span class="pre">None</span></tt> (no argument expected), then <tt class="docutils literal"><span class="pre">value</span></tt> will be <tt class="xref docutils literal"><span class="pre">None</span></tt>.  If <tt class="docutils literal"><span class="pre">nargs</span></tt>
&gt; 1, <tt class="docutils literal"><span class="pre">value</span></tt> will be a tuple of values of the appropriate type.</dd>
<dt><tt class="docutils literal"><span class="pre">parser</span></tt></dt>
<dd><p class="first">is the OptionParser instance driving the whole thing, mainly useful because you
can access some other interesting data through its instance attributes:</p>
<dl class="last docutils">
<dt><tt class="docutils literal"><span class="pre">parser.largs</span></tt></dt>
<dd>the current list of leftover arguments, ie. arguments that have been consumed
but are neither options nor option arguments. Feel free to modify
<tt class="docutils literal"><span class="pre">parser.largs</span></tt>, e.g. by adding more arguments to it.  (This list will become
<tt class="docutils literal"><span class="pre">args</span></tt>, the second return value of <tt class="xref docutils literal"><span class="pre">parse_args()</span></tt>.)</dd>
<dt><tt class="docutils literal"><span class="pre">parser.rargs</span></tt></dt>
<dd>the current list of remaining arguments, ie. with <tt class="docutils literal"><span class="pre">opt_str</span></tt> and <tt class="docutils literal"><span class="pre">value</span></tt> (if
applicable) removed, and only the arguments following them still there.  Feel
free to modify <tt class="docutils literal"><span class="pre">parser.rargs</span></tt>, e.g. by consuming more arguments.</dd>
<dt><tt class="docutils literal"><span class="pre">parser.values</span></tt></dt>
<dd>the object where option values are by default stored (an instance of
optparse.OptionValues).  This lets callbacks use the same mechanism as the rest
of <tt class="xref docutils literal"><span class="pre">optparse</span></tt> for storing option values; you don&#8217;t need to mess around with
globals or closures.  You can also access or modify the value(s) of any options
already encountered on the command-line.</dd>
</dl>
</dd>
<dt><tt class="docutils literal"><span class="pre">args</span></tt></dt>
<dd>is a tuple of arbitrary positional arguments supplied via the <tt class="docutils literal"><span class="pre">callback_args</span></tt>
option attribute.</dd>
<dt><tt class="docutils literal"><span class="pre">kwargs</span></tt></dt>
<dd>is a dictionary of arbitrary keyword arguments supplied via <tt class="docutils literal"><span class="pre">callback_kwargs</span></tt>.</dd>
</dl>
</div>
<div class="section" id="raising-errors-in-a-callback">
<span id="optparse-raising-errors-in-callback"></span><h3>16.4.4.3. Raising errors in a callback<a class="headerlink" href="#raising-errors-in-a-callback" title="Permalink to this headline">¶</a></h3>
<p>The callback function should raise <tt class="xref docutils literal"><span class="pre">OptionValueError</span></tt> if there are any problems
with the option or its argument(s).  <tt class="xref docutils literal"><span class="pre">optparse</span></tt> catches this and terminates
the program, printing the error message you supply to stderr.  Your message
should be clear, concise, accurate, and mention the option at fault.  Otherwise,
the user will have a hard time figuring out what he did wrong.</p>
</div>
<div class="section" id="callback-example-1-trivial-callback">
<span id="optparse-callback-example-1"></span><h3>16.4.4.4. Callback example 1: trivial callback<a class="headerlink" href="#callback-example-1-trivial-callback" title="Permalink to this headline">¶</a></h3>
<p>Here&#8217;s an example of a callback option that takes no arguments, and simply
records that the option was seen:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">record_foo_seen</span><span class="p">(</span><span class="n">option</span><span class="p">,</span> <span class="n">opt_str</span><span class="p">,</span> <span class="n">value</span><span class="p">,</span> <span class="n">parser</span><span class="p">):</span>
    <span class="n">parser</span><span class="o">.</span><span class="n">values</span><span class="o">.</span><span class="n">saw_foo</span> <span class="o">=</span> <span class="bp">True</span>

<span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s">&quot;--foo&quot;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s">&quot;callback&quot;</span><span class="p">,</span> <span class="n">callback</span><span class="o">=</span><span class="n">record_foo_seen</span><span class="p">)</span>
</pre></div>
</div>
<p>Of course, you could do that with the <tt class="docutils literal"><span class="pre">store_true</span></tt> action.</p>
</div>
<div class="section" id="callback-example-2-check-option-order">
<span id="optparse-callback-example-2"></span><h3>16.4.4.5. Callback example 2: check option order<a class="headerlink" href="#callback-example-2-check-option-order" title="Permalink to this headline">¶</a></h3>
<p>Here&#8217;s a slightly more interesting example: record the fact that <tt class="docutils literal"><span class="pre">&quot;-a&quot;</span></tt> is
seen, but blow up if it comes after <tt class="docutils literal"><span class="pre">&quot;-b&quot;</span></tt> in the command-line.</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">check_order</span><span class="p">(</span><span class="n">option</span><span class="p">,</span> <span class="n">opt_str</span><span class="p">,</span> <span class="n">value</span><span class="p">,</span> <span class="n">parser</span><span class="p">):</span>
    <span class="k">if</span> <span class="n">parser</span><span class="o">.</span><span class="n">values</span><span class="o">.</span><span class="n">b</span><span class="p">:</span>
        <span class="k">raise</span> <span class="n">OptionValueError</span><span class="p">(</span><span class="s">&quot;can&#39;t use -a after -b&quot;</span><span class="p">)</span>
    <span class="n">parser</span><span class="o">.</span><span class="n">values</span><span class="o">.</span><span class="n">a</span> <span class="o">=</span> <span class="mf">1</span>
<span class="p">[</span><span class="o">...</span><span class="p">]</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s">&quot;-a&quot;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s">&quot;callback&quot;</span><span class="p">,</span> <span class="n">callback</span><span class="o">=</span><span class="n">check_order</span><span class="p">)</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s">&quot;-b&quot;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s">&quot;store_true&quot;</span><span class="p">,</span> <span class="n">dest</span><span class="o">=</span><span class="s">&quot;b&quot;</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="section" id="callback-example-3-check-option-order-generalized">
<span id="optparse-callback-example-3"></span><h3>16.4.4.6. Callback example 3: check option order (generalized)<a class="headerlink" href="#callback-example-3-check-option-order-generalized" title="Permalink to this headline">¶</a></h3>
<p>If you want to re-use this callback for several similar options (set a flag, but
blow up if <tt class="docutils literal"><span class="pre">&quot;-b&quot;</span></tt> has already been seen), it needs a bit of work: the error
message and the flag that it sets must be generalized.</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">check_order</span><span class="p">(</span><span class="n">option</span><span class="p">,</span> <span class="n">opt_str</span><span class="p">,</span> <span class="n">value</span><span class="p">,</span> <span class="n">parser</span><span class="p">):</span>
    <span class="k">if</span> <span class="n">parser</span><span class="o">.</span><span class="n">values</span><span class="o">.</span><span class="n">b</span><span class="p">:</span>
        <span class="k">raise</span> <span class="n">OptionValueError</span><span class="p">(</span><span class="s">&quot;can&#39;t use </span><span class="si">%s</span><span class="s"> after -b&quot;</span> <span class="o">%</span> <span class="n">opt_str</span><span class="p">)</span>
    <span class="nb">setattr</span><span class="p">(</span><span class="n">parser</span><span class="o">.</span><span class="n">values</span><span class="p">,</span> <span class="n">option</span><span class="o">.</span><span class="n">dest</span><span class="p">,</span> <span class="mf">1</span><span class="p">)</span>
<span class="p">[</span><span class="o">...</span><span class="p">]</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s">&quot;-a&quot;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s">&quot;callback&quot;</span><span class="p">,</span> <span class="n">callback</span><span class="o">=</span><span class="n">check_order</span><span class="p">,</span> <span class="n">dest</span><span class="o">=</span><span class="s">&#39;a&#39;</span><span class="p">)</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s">&quot;-b&quot;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s">&quot;store_true&quot;</span><span class="p">,</span> <span class="n">dest</span><span class="o">=</span><span class="s">&quot;b&quot;</span><span class="p">)</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s">&quot;-c&quot;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s">&quot;callback&quot;</span><span class="p">,</span> <span class="n">callback</span><span class="o">=</span><span class="n">check_order</span><span class="p">,</span> <span class="n">dest</span><span class="o">=</span><span class="s">&#39;c&#39;</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="section" id="callback-example-4-check-arbitrary-condition">
<span id="optparse-callback-example-4"></span><h3>16.4.4.7. Callback example 4: check arbitrary condition<a class="headerlink" href="#callback-example-4-check-arbitrary-condition" title="Permalink to this headline">¶</a></h3>
<p>Of course, you could put any condition in there&#8212;you&#8217;re not limited to checking
the values of already-defined options.  For example, if you have options that
should not be called when the moon is full, all you have to do is this:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">check_moon</span><span class="p">(</span><span class="n">option</span><span class="p">,</span> <span class="n">opt_str</span><span class="p">,</span> <span class="n">value</span><span class="p">,</span> <span class="n">parser</span><span class="p">):</span>
    <span class="k">if</span> <span class="n">is_moon_full</span><span class="p">():</span>
        <span class="k">raise</span> <span class="n">OptionValueError</span><span class="p">(</span><span class="s">&quot;</span><span class="si">%s</span><span class="s"> option invalid when moon is full&quot;</span>
                               <span class="o">%</span> <span class="n">opt_str</span><span class="p">)</span>
    <span class="nb">setattr</span><span class="p">(</span><span class="n">parser</span><span class="o">.</span><span class="n">values</span><span class="p">,</span> <span class="n">option</span><span class="o">.</span><span class="n">dest</span><span class="p">,</span> <span class="mf">1</span><span class="p">)</span>
<span class="p">[</span><span class="o">...</span><span class="p">]</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s">&quot;--foo&quot;</span><span class="p">,</span>
                  <span class="n">action</span><span class="o">=</span><span class="s">&quot;callback&quot;</span><span class="p">,</span> <span class="n">callback</span><span class="o">=</span><span class="n">check_moon</span><span class="p">,</span> <span class="n">dest</span><span class="o">=</span><span class="s">&quot;foo&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>(The definition of <tt class="docutils literal"><span class="pre">is_moon_full()</span></tt> is left as an exercise for the reader.)</p>
</div>
<div class="section" id="callback-example-5-fixed-arguments">
<span id="optparse-callback-example-5"></span><h3>16.4.4.8. Callback example 5: fixed arguments<a class="headerlink" href="#callback-example-5-fixed-arguments" title="Permalink to this headline">¶</a></h3>
<p>Things get slightly more interesting when you define callback options that take
a fixed number of arguments.  Specifying that a callback option takes arguments
is similar to defining a <tt class="docutils literal"><span class="pre">store</span></tt> or <tt class="docutils literal"><span class="pre">append</span></tt> option: if you define
<a title="type" class="reference external" href="functions.html#type"><tt class="xref docutils literal"><span class="pre">type</span></tt></a>, then the option takes one argument that must be convertible to
that type; if you further define <tt class="docutils literal"><span class="pre">nargs</span></tt>, then the option takes <tt class="docutils literal"><span class="pre">nargs</span></tt>
arguments.</p>
<p>Here&#8217;s an example that just emulates the standard <tt class="docutils literal"><span class="pre">store</span></tt> action:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">store_value</span><span class="p">(</span><span class="n">option</span><span class="p">,</span> <span class="n">opt_str</span><span class="p">,</span> <span class="n">value</span><span class="p">,</span> <span class="n">parser</span><span class="p">):</span>
    <span class="nb">setattr</span><span class="p">(</span><span class="n">parser</span><span class="o">.</span><span class="n">values</span><span class="p">,</span> <span class="n">option</span><span class="o">.</span><span class="n">dest</span><span class="p">,</span> <span class="n">value</span><span class="p">)</span>
<span class="p">[</span><span class="o">...</span><span class="p">]</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s">&quot;--foo&quot;</span><span class="p">,</span>
                  <span class="n">action</span><span class="o">=</span><span class="s">&quot;callback&quot;</span><span class="p">,</span> <span class="n">callback</span><span class="o">=</span><span class="n">store_value</span><span class="p">,</span>
                  <span class="nb">type</span><span class="o">=</span><span class="s">&quot;int&quot;</span><span class="p">,</span> <span class="n">nargs</span><span class="o">=</span><span class="mf">3</span><span class="p">,</span> <span class="n">dest</span><span class="o">=</span><span class="s">&quot;foo&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>Note that <tt class="xref docutils literal"><span class="pre">optparse</span></tt> takes care of consuming 3 arguments and converting
them to integers for you; all you have to do is store them.  (Or whatever;
obviously you don&#8217;t need a callback for this example.)</p>
</div>
<div class="section" id="callback-example-6-variable-arguments">
<span id="optparse-callback-example-6"></span><h3>16.4.4.9. Callback example 6: variable arguments<a class="headerlink" href="#callback-example-6-variable-arguments" title="Permalink to this headline">¶</a></h3>
<p>Things get hairy when you want an option to take a variable number of arguments.
For this case, you must write a callback, as <tt class="xref docutils literal"><span class="pre">optparse</span></tt> doesn&#8217;t provide any
built-in capabilities for it.  And you have to deal with certain intricacies of
conventional Unix command-line parsing that <tt class="xref docutils literal"><span class="pre">optparse</span></tt> normally handles for
you.  In particular, callbacks should implement the conventional rules for bare
<tt class="docutils literal"><span class="pre">&quot;--&quot;</span></tt> and <tt class="docutils literal"><span class="pre">&quot;-&quot;</span></tt> arguments:</p>
<ul class="simple">
<li>either <tt class="docutils literal"><span class="pre">&quot;--&quot;</span></tt> or <tt class="docutils literal"><span class="pre">&quot;-&quot;</span></tt> can be option arguments</li>
<li>bare <tt class="docutils literal"><span class="pre">&quot;--&quot;</span></tt> (if not the argument to some option): halt command-line
processing and discard the <tt class="docutils literal"><span class="pre">&quot;--&quot;</span></tt></li>
<li>bare <tt class="docutils literal"><span class="pre">&quot;-&quot;</span></tt> (if not the argument to some option): halt command-line
processing but keep the <tt class="docutils literal"><span class="pre">&quot;-&quot;</span></tt> (append it to <tt class="docutils literal"><span class="pre">parser.largs</span></tt>)</li>
</ul>
<p>If you want an option that takes a variable number of arguments, there are
several subtle, tricky issues to worry about.  The exact implementation you
choose will be based on which trade-offs you&#8217;re willing to make for your
application (which is why <tt class="xref docutils literal"><span class="pre">optparse</span></tt> doesn&#8217;t support this sort of thing
directly).</p>
<p>Nevertheless, here&#8217;s a stab at a callback for an option with variable
arguments:</p>
<div class="highlight-python"><pre> def vararg_callback(option, opt_str, value, parser):
     assert value is None
     value = []

     def floatable(str):
         try:
             float(str)
             return True
         except ValueError:
             return False

     for arg in parser.rargs:
         # stop on --foo like options
         if arg[:2] == "--" and len(arg) &gt; 2:
             break
         # stop on -a, but not on -3 or -3.0
         if arg[:1] == "-" and len(arg) &gt; 1 and not floatable(arg):
             break
         value.append(arg)

     del parser.rargs[:len(value)]
     setattr(parser.values, option.dest, value)

[...]
parser.add_option("-c", "--callback", dest="vararg_attr",
                  action="callback", callback=vararg_callback)</pre>
</div>
</div>
</div>
<div class="section" id="extending-optparse">
<span id="optparse-extending-optparse"></span><h2>16.4.5. Extending <tt class="xref docutils literal"><span class="pre">optparse</span></tt><a class="headerlink" href="#extending-optparse" title="Permalink to this headline">¶</a></h2>
<p>Since the two major controlling factors in how <tt class="xref docutils literal"><span class="pre">optparse</span></tt> interprets
command-line options are the action and type of each option, the most likely
direction of extension is to add new actions and new types.</p>
<div class="section" id="adding-new-types">
<span id="optparse-adding-new-types"></span><h3>16.4.5.1. Adding new types<a class="headerlink" href="#adding-new-types" title="Permalink to this headline">¶</a></h3>
<p>To add new types, you need to define your own subclass of <tt class="xref docutils literal"><span class="pre">optparse</span></tt>&#8216;s
Option class.  This class has a couple of attributes that define
<tt class="xref docutils literal"><span class="pre">optparse</span></tt>&#8216;s types: <tt class="xref docutils literal"><span class="pre">TYPES</span></tt> and <tt class="xref docutils literal"><span class="pre">TYPE_CHECKER</span></tt>.</p>
<p><tt class="xref docutils literal"><span class="pre">TYPES</span></tt> is a tuple of type names; in your subclass, simply define a new
tuple <tt class="xref docutils literal"><span class="pre">TYPES</span></tt> that builds on the standard one.</p>
<p><tt class="xref docutils literal"><span class="pre">TYPE_CHECKER</span></tt> is a dictionary mapping type names to type-checking
functions.  A type-checking function has the following signature:</p>
<div class="highlight-python"><pre>def check_mytype(option, opt, value)</pre>
</div>
<p>where <tt class="docutils literal"><span class="pre">option</span></tt> is an <tt class="xref docutils literal"><span class="pre">Option</span></tt> instance, <tt class="docutils literal"><span class="pre">opt</span></tt> is an option string
(e.g., <tt class="docutils literal"><span class="pre">&quot;-f&quot;</span></tt>), and <tt class="docutils literal"><span class="pre">value</span></tt> is the string from the command line that must be
checked and converted to your desired type.  <tt class="docutils literal"><span class="pre">check_mytype()</span></tt> should return an
object of the hypothetical type <tt class="docutils literal"><span class="pre">mytype</span></tt>.  The value returned by a
type-checking function will wind up in the OptionValues instance returned by
<tt class="xref docutils literal"><span class="pre">OptionParser.parse_args()</span></tt>, or be passed to a callback as the <tt class="docutils literal"><span class="pre">value</span></tt>
parameter.</p>
<p>Your type-checking function should raise <tt class="xref docutils literal"><span class="pre">OptionValueError</span></tt> if it encounters any
problems.  <tt class="xref docutils literal"><span class="pre">OptionValueError</span></tt> takes a single string argument, which is passed
as-is to <tt class="xref docutils literal"><span class="pre">OptionParser</span></tt>&#8216;s <tt class="xref docutils literal"><span class="pre">error()</span></tt> method, which in turn prepends the program
name and the string <tt class="docutils literal"><span class="pre">&quot;error:&quot;</span></tt> and prints everything to stderr before
terminating the process.</p>
<p>Here&#8217;s a silly example that demonstrates adding a <tt class="docutils literal"><span class="pre">complex</span></tt> option type to
parse Python-style complex numbers on the command line.  (This is even sillier
than it used to be, because <tt class="xref docutils literal"><span class="pre">optparse</span></tt> 1.3 added built-in support for
complex numbers, but never mind.)</p>
<p>First, the necessary imports:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">copy</span> <span class="kn">import</span> <span class="n">copy</span>
<span class="kn">from</span> <span class="nn">optparse</span> <span class="kn">import</span> <span class="n">Option</span><span class="p">,</span> <span class="n">OptionValueError</span>
</pre></div>
</div>
<p>You need to define your type-checker first, since it&#8217;s referred to later (in the
<tt class="xref docutils literal"><span class="pre">TYPE_CHECKER</span></tt> class attribute of your Option subclass):</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">check_complex</span><span class="p">(</span><span class="n">option</span><span class="p">,</span> <span class="n">opt</span><span class="p">,</span> <span class="n">value</span><span class="p">):</span>
    <span class="k">try</span><span class="p">:</span>
        <span class="k">return</span> <span class="nb">complex</span><span class="p">(</span><span class="n">value</span><span class="p">)</span>
    <span class="k">except</span> <span class="ne">ValueError</span><span class="p">:</span>
        <span class="k">raise</span> <span class="n">OptionValueError</span><span class="p">(</span>
            <span class="s">&quot;option </span><span class="si">%s</span><span class="s">: invalid complex value: </span><span class="si">%r</span><span class="s">&quot;</span> <span class="o">%</span> <span class="p">(</span><span class="n">opt</span><span class="p">,</span> <span class="n">value</span><span class="p">))</span>
</pre></div>
</div>
<p>Finally, the Option subclass:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">MyOption</span> <span class="p">(</span><span class="n">Option</span><span class="p">):</span>
    <span class="n">TYPES</span> <span class="o">=</span> <span class="n">Option</span><span class="o">.</span><span class="n">TYPES</span> <span class="o">+</span> <span class="p">(</span><span class="s">&quot;complex&quot;</span><span class="p">,)</span>
    <span class="n">TYPE_CHECKER</span> <span class="o">=</span> <span class="n">copy</span><span class="p">(</span><span class="n">Option</span><span class="o">.</span><span class="n">TYPE_CHECKER</span><span class="p">)</span>
    <span class="n">TYPE_CHECKER</span><span class="p">[</span><span class="s">&quot;complex&quot;</span><span class="p">]</span> <span class="o">=</span> <span class="n">check_complex</span>
</pre></div>
</div>
<p>(If we didn&#8217;t make a <tt class="xref docutils literal"><span class="pre">copy()</span></tt> of <tt class="xref docutils literal"><span class="pre">Option.TYPE_CHECKER</span></tt>, we would end
up modifying the <tt class="xref docutils literal"><span class="pre">TYPE_CHECKER</span></tt> attribute of <tt class="xref docutils literal"><span class="pre">optparse</span></tt>&#8216;s Option
class. This being Python, nothing stops you from doing that except good manners
and common sense.)</p>
<p>That&#8217;s it!  Now you can write a script that uses the new option type just like
any other <tt class="xref docutils literal"><span class="pre">optparse</span></tt>-based script, except you have to instruct your
OptionParser to use MyOption instead of Option:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">parser</span> <span class="o">=</span> <span class="n">OptionParser</span><span class="p">(</span><span class="n">option_class</span><span class="o">=</span><span class="n">MyOption</span><span class="p">)</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s">&quot;-c&quot;</span><span class="p">,</span> <span class="nb">type</span><span class="o">=</span><span class="s">&quot;complex&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>Alternately, you can build your own option list and pass it to OptionParser; if
you don&#8217;t use <tt class="xref docutils literal"><span class="pre">add_option()</span></tt> in the above way, you don&#8217;t need to tell
OptionParser which option class to use:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">option_list</span> <span class="o">=</span> <span class="p">[</span><span class="n">MyOption</span><span class="p">(</span><span class="s">&quot;-c&quot;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s">&quot;store&quot;</span><span class="p">,</span> <span class="nb">type</span><span class="o">=</span><span class="s">&quot;complex&quot;</span><span class="p">,</span> <span class="n">dest</span><span class="o">=</span><span class="s">&quot;c&quot;</span><span class="p">)]</span>
<span class="n">parser</span> <span class="o">=</span> <span class="n">OptionParser</span><span class="p">(</span><span class="n">option_list</span><span class="o">=</span><span class="n">option_list</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="section" id="adding-new-actions">
<span id="optparse-adding-new-actions"></span><h3>16.4.5.2. Adding new actions<a class="headerlink" href="#adding-new-actions" title="Permalink to this headline">¶</a></h3>
<p>Adding new actions is a bit trickier, because you have to understand that
<tt class="xref docutils literal"><span class="pre">optparse</span></tt> has a couple of classifications for actions:</p>
<dl class="docutils">
<dt>&#8220;store&#8221; actions</dt>
<dd>actions that result in <tt class="xref docutils literal"><span class="pre">optparse</span></tt> storing a value to an attribute of the
current OptionValues instance; these options require a <tt class="xref docutils literal"><span class="pre">dest</span></tt> attribute to
be supplied to the Option constructor</dd>
<dt>&#8220;typed&#8221; actions</dt>
<dd>actions that take a value from the command line and expect it to be of a certain
type; or rather, a string that can be converted to a certain type.  These
options require a <a title="type" class="reference external" href="functions.html#type"><tt class="xref docutils literal"><span class="pre">type</span></tt></a> attribute to the Option constructor.</dd>
</dl>
<p>These are overlapping sets: some default &#8220;store&#8221; actions are <tt class="docutils literal"><span class="pre">store</span></tt>,
<tt class="docutils literal"><span class="pre">store_const</span></tt>, <tt class="docutils literal"><span class="pre">append</span></tt>, and <tt class="docutils literal"><span class="pre">count</span></tt>, while the default &#8220;typed&#8221; actions
are <tt class="docutils literal"><span class="pre">store</span></tt>, <tt class="docutils literal"><span class="pre">append</span></tt>, and <tt class="docutils literal"><span class="pre">callback</span></tt>.</p>
<p>When you add an action, you need to categorize it by listing it in at least one
of the following class attributes of Option (all are lists of strings):</p>
<dl class="docutils">
<dt><tt class="xref docutils literal"><span class="pre">ACTIONS</span></tt></dt>
<dd>all actions must be listed in ACTIONS</dd>
<dt><tt class="xref docutils literal"><span class="pre">STORE_ACTIONS</span></tt></dt>
<dd>&#8220;store&#8221; actions are additionally listed here</dd>
<dt><tt class="xref docutils literal"><span class="pre">TYPED_ACTIONS</span></tt></dt>
<dd>&#8220;typed&#8221; actions are additionally listed here</dd>
<dt><tt class="docutils literal"><span class="pre">ALWAYS_TYPED_ACTIONS</span></tt></dt>
<dd>actions that always take a type (i.e. whose options always take a value) are
additionally listed here.  The only effect of this is that <tt class="xref docutils literal"><span class="pre">optparse</span></tt>
assigns the default type, <tt class="docutils literal"><span class="pre">string</span></tt>, to options with no explicit type whose
action is listed in <tt class="docutils literal"><span class="pre">ALWAYS_TYPED_ACTIONS</span></tt>.</dd>
</dl>
<p>In order to actually implement your new action, you must override Option&#8217;s
<tt class="xref docutils literal"><span class="pre">take_action()</span></tt> method and add a case that recognizes your action.</p>
<p>For example, let&#8217;s add an <tt class="docutils literal"><span class="pre">extend</span></tt> action.  This is similar to the standard
<tt class="docutils literal"><span class="pre">append</span></tt> action, but instead of taking a single value from the command-line
and appending it to an existing list, <tt class="docutils literal"><span class="pre">extend</span></tt> will take multiple values in a
single comma-delimited string, and extend an existing list with them.  That is,
if <tt class="docutils literal"><span class="pre">&quot;--names&quot;</span></tt> is an <tt class="docutils literal"><span class="pre">extend</span></tt> option of type <tt class="docutils literal"><span class="pre">string</span></tt>, the command line</p>
<div class="highlight-python"><pre>--names=foo,bar --names blah --names ding,dong</pre>
</div>
<p>would result in a list</p>
<div class="highlight-python"><div class="highlight"><pre><span class="p">[</span><span class="s">&quot;foo&quot;</span><span class="p">,</span> <span class="s">&quot;bar&quot;</span><span class="p">,</span> <span class="s">&quot;blah&quot;</span><span class="p">,</span> <span class="s">&quot;ding&quot;</span><span class="p">,</span> <span class="s">&quot;dong&quot;</span><span class="p">]</span>
</pre></div>
</div>
<p>Again we define a subclass of Option:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">MyOption</span> <span class="p">(</span><span class="n">Option</span><span class="p">):</span>

    <span class="n">ACTIONS</span> <span class="o">=</span> <span class="n">Option</span><span class="o">.</span><span class="n">ACTIONS</span> <span class="o">+</span> <span class="p">(</span><span class="s">&quot;extend&quot;</span><span class="p">,)</span>
    <span class="n">STORE_ACTIONS</span> <span class="o">=</span> <span class="n">Option</span><span class="o">.</span><span class="n">STORE_ACTIONS</span> <span class="o">+</span> <span class="p">(</span><span class="s">&quot;extend&quot;</span><span class="p">,)</span>
    <span class="n">TYPED_ACTIONS</span> <span class="o">=</span> <span class="n">Option</span><span class="o">.</span><span class="n">TYPED_ACTIONS</span> <span class="o">+</span> <span class="p">(</span><span class="s">&quot;extend&quot;</span><span class="p">,)</span>
    <span class="n">ALWAYS_TYPED_ACTIONS</span> <span class="o">=</span> <span class="n">Option</span><span class="o">.</span><span class="n">ALWAYS_TYPED_ACTIONS</span> <span class="o">+</span> <span class="p">(</span><span class="s">&quot;extend&quot;</span><span class="p">,)</span>

    <span class="k">def</span> <span class="nf">take_action</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">action</span><span class="p">,</span> <span class="n">dest</span><span class="p">,</span> <span class="n">opt</span><span class="p">,</span> <span class="n">value</span><span class="p">,</span> <span class="n">values</span><span class="p">,</span> <span class="n">parser</span><span class="p">):</span>
        <span class="k">if</span> <span class="n">action</span> <span class="o">==</span> <span class="s">&quot;extend&quot;</span><span class="p">:</span>
            <span class="n">lvalue</span> <span class="o">=</span> <span class="n">value</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="s">&quot;,&quot;</span><span class="p">)</span>
            <span class="n">values</span><span class="o">.</span><span class="n">ensure_value</span><span class="p">(</span><span class="n">dest</span><span class="p">,</span> <span class="p">[])</span><span class="o">.</span><span class="n">extend</span><span class="p">(</span><span class="n">lvalue</span><span class="p">)</span>
        <span class="k">else</span><span class="p">:</span>
            <span class="n">Option</span><span class="o">.</span><span class="n">take_action</span><span class="p">(</span>
                <span class="bp">self</span><span class="p">,</span> <span class="n">action</span><span class="p">,</span> <span class="n">dest</span><span class="p">,</span> <span class="n">opt</span><span class="p">,</span> <span class="n">value</span><span class="p">,</span> <span class="n">values</span><span class="p">,</span> <span class="n">parser</span><span class="p">)</span>
</pre></div>
</div>
<p>Features of note:</p>
<ul>
<li><p class="first"><tt class="docutils literal"><span class="pre">extend</span></tt> both expects a value on the command-line and stores that value
somewhere, so it goes in both <tt class="xref docutils literal"><span class="pre">STORE_ACTIONS</span></tt> and <tt class="xref docutils literal"><span class="pre">TYPED_ACTIONS</span></tt></p>
</li>
<li><p class="first">to ensure that <tt class="xref docutils literal"><span class="pre">optparse</span></tt> assigns the default type of <tt class="docutils literal"><span class="pre">string</span></tt> to
<tt class="docutils literal"><span class="pre">extend</span></tt> actions, we put the <tt class="docutils literal"><span class="pre">extend</span></tt> action in <tt class="docutils literal"><span class="pre">ALWAYS_TYPED_ACTIONS</span></tt> as
well</p>
</li>
<li><p class="first"><tt class="xref docutils literal"><span class="pre">MyOption.take_action()</span></tt> implements just this one new action, and passes
control back to <tt class="xref docutils literal"><span class="pre">Option.take_action()</span></tt> for the standard <tt class="xref docutils literal"><span class="pre">optparse</span></tt>
actions</p>
</li>
<li><p class="first"><tt class="docutils literal"><span class="pre">values</span></tt> is an instance of the optparse_parser.Values class, which
provides the very useful <tt class="xref docutils literal"><span class="pre">ensure_value()</span></tt> method. <tt class="xref docutils literal"><span class="pre">ensure_value()</span></tt> is
essentially <a title="getattr" class="reference external" href="functions.html#getattr"><tt class="xref docutils literal"><span class="pre">getattr()</span></tt></a> with a safety valve; it is called as</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">values</span><span class="o">.</span><span class="n">ensure_value</span><span class="p">(</span><span class="n">attr</span><span class="p">,</span> <span class="n">value</span><span class="p">)</span>
</pre></div>
</div>
<p>If the <tt class="docutils literal"><span class="pre">attr</span></tt> attribute of <tt class="docutils literal"><span class="pre">values</span></tt> doesn&#8217;t exist or is None, then
ensure_value() first sets it to <tt class="docutils literal"><span class="pre">value</span></tt>, and then returns &#8216;value. This is very
handy for actions like <tt class="docutils literal"><span class="pre">extend</span></tt>, <tt class="docutils literal"><span class="pre">append</span></tt>, and <tt class="docutils literal"><span class="pre">count</span></tt>, all of which
accumulate data in a variable and expect that variable to be of a certain type
(a list for the first two, an integer for the latter).  Using
<tt class="xref docutils literal"><span class="pre">ensure_value()</span></tt> means that scripts using your action don&#8217;t have to worry
about setting a default value for the option destinations in question; they can
just leave the default as None and <tt class="xref docutils literal"><span class="pre">ensure_value()</span></tt> will take care of
getting it right when it&#8217;s needed.</p>
</li>
</ul>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar">
        <div class="sphinxsidebarwrapper">
            <h3><a href="../contents.html">Table Of Contents</a></h3>
            <ul>
<li><a class="reference external" href="">16.4. <tt class="docutils literal"><span class="pre">optparse</span></tt> &#8212; More powerful command line option parser</a><ul>
<li><a class="reference external" href="#background">16.4.1. Background</a><ul>
<li><a class="reference external" href="#terminology">16.4.1.1. Terminology</a></li>
<li><a class="reference external" href="#what-are-options-for">16.4.1.2. What are options for?</a></li>
<li><a class="reference external" href="#what-are-positional-arguments-for">16.4.1.3. What are positional arguments for?</a></li>
</ul>
</li>
<li><a class="reference external" href="#tutorial">16.4.2. Tutorial</a><ul>
<li><a class="reference external" href="#understanding-option-actions">16.4.2.1. Understanding option actions</a></li>
<li><a class="reference external" href="#the-store-action">16.4.2.2. The store action</a></li>
<li><a class="reference external" href="#handling-boolean-flag-options">16.4.2.3. Handling boolean (flag) options</a></li>
<li><a class="reference external" href="#other-actions">16.4.2.4. Other actions</a></li>
<li><a class="reference external" href="#default-values">16.4.2.5. Default values</a></li>
<li><a class="reference external" href="#generating-help">16.4.2.6. Generating help</a></li>
<li><a class="reference external" href="#printing-a-version-string">16.4.2.7. Printing a version string</a></li>
<li><a class="reference external" href="#how-optparse-handles-errors">16.4.2.8. How <tt class="docutils literal"><span class="pre">optparse</span></tt> handles errors</a></li>
<li><a class="reference external" href="#putting-it-all-together">16.4.2.9. Putting it all together</a></li>
</ul>
</li>
<li><a class="reference external" href="#reference-guide">16.4.3. Reference Guide</a><ul>
<li><a class="reference external" href="#creating-the-parser">16.4.3.1. Creating the parser</a></li>
<li><a class="reference external" href="#populating-the-parser">16.4.3.2. Populating the parser</a></li>
<li><a class="reference external" href="#defining-options">16.4.3.3. Defining options</a></li>
<li><a class="reference external" href="#standard-option-actions">16.4.3.4. Standard option actions</a></li>
<li><a class="reference external" href="#option-attributes">16.4.3.5. Option attributes</a></li>
<li><a class="reference external" href="#standard-option-types">16.4.3.6. Standard option types</a></li>
<li><a class="reference external" href="#parsing-arguments">16.4.3.7. Parsing arguments</a></li>
<li><a class="reference external" href="#querying-and-manipulating-your-option-parser">16.4.3.8. Querying and manipulating your option parser</a></li>
<li><a class="reference external" href="#conflicts-between-options">16.4.3.9. Conflicts between options</a></li>
<li><a class="reference external" href="#cleanup">16.4.3.10. Cleanup</a></li>
<li><a class="reference external" href="#other-methods">16.4.3.11. Other methods</a></li>
</ul>
</li>
<li><a class="reference external" href="#option-callbacks">16.4.4. Option Callbacks</a><ul>
<li><a class="reference external" href="#defining-a-callback-option">16.4.4.1. Defining a callback option</a></li>
<li><a class="reference external" href="#how-callbacks-are-called">16.4.4.2. How callbacks are called</a></li>
<li><a class="reference external" href="#raising-errors-in-a-callback">16.4.4.3. Raising errors in a callback</a></li>
<li><a class="reference external" href="#callback-example-1-trivial-callback">16.4.4.4. Callback example 1: trivial callback</a></li>
<li><a class="reference external" href="#callback-example-2-check-option-order">16.4.4.5. Callback example 2: check option order</a></li>
<li><a class="reference external" href="#callback-example-3-check-option-order-generalized">16.4.4.6. Callback example 3: check option order (generalized)</a></li>
<li><a class="reference external" href="#callback-example-4-check-arbitrary-condition">16.4.4.7. Callback example 4: check arbitrary condition</a></li>
<li><a class="reference external" href="#callback-example-5-fixed-arguments">16.4.4.8. Callback example 5: fixed arguments</a></li>
<li><a class="reference external" href="#callback-example-6-variable-arguments">16.4.4.9. Callback example 6: variable arguments</a></li>
</ul>
</li>
<li><a class="reference external" href="#extending-optparse">16.4.5. Extending <tt class="docutils literal"><span class="pre">optparse</span></tt></a><ul>
<li><a class="reference external" href="#adding-new-types">16.4.5.1. Adding new types</a></li>
<li><a class="reference external" href="#adding-new-actions">16.4.5.2. Adding new actions</a></li>
</ul>
</li>
</ul>
</li>
</ul>

            <h4>Previous topic</h4>
            <p class="topless"><a href="time.html"
                                  title="previous chapter">16.3. <tt class="docutils literal docutils literal"><span class="pre">time</span></tt> &#8212; Time access and conversions</a></p>
            <h4>Next topic</h4>
            <p class="topless"><a href="getopt.html"
                                  title="next chapter">16.5. <tt class="docutils literal docutils literal docutils literal"><span class="pre">getopt</span></tt> &#8212; Parser for command line options</a></p>
            <h3>This Page</h3>
            <ul class="this-page-menu">
              <li><a href="../_sources/library/optparse.txt"
                     rel="nofollow">Show Source</a></li>
            </ul>
          <div id="searchbox" style="display: none">
            <h3>Quick search</h3>
              <form class="search" action="../search.html" method="get">
                <input type="text" name="q" size="18" />
                <input type="submit" value="Go" />
                <input type="hidden" name="check_keywords" value="yes" />
                <input type="hidden" name="area" value="default" />
              </form>
              <p class="searchtip" style="font-size: 90%">
              Enter search terms or a module, class or function name.
              </p>
          </div>
          <script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>
    <div class="related">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../modindex.html" title="Global Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="getopt.html" title="16.5. getopt — Parser for command line options"
             >next</a> |</li>
        <li class="right" >
          <a href="time.html" title="16.3. time — Time access and conversions"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="../index.html">Python v2.6.2 documentation</a> &raquo;</li>

          <li><a href="index.html" >The Python Standard Library</a> &raquo;</li>
          <li><a href="allos.html" >16. Generic Operating System Services</a> &raquo;</li> 
      </ul>
    </div>
    <div class="footer">
      &copy; <a href="../copyright.html">Copyright</a> 1990-2009, Python Software Foundation.
      Last updated on Apr 15, 2009.
      Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 0.6.1.
    </div>
  </body>
</html>